如何动态居中div css的高度和宽度

时间:2017-03-11 12:47:38

标签: javascript jquery html css

我一直在尝试创建一些图片库,我希望.lightboxCenter类保留在页面的中心,但是缩小屏幕的尺寸会减小。我该怎么做呢?此外,当我调整窗口大小时,div覆盖了,我该如何阻止这种情况发生。 非常感谢。 https://jsfiddle.net/36jkh1hj/

.lightboxBackground {
  width:            100%;
  height:           100%;
  top:              0;
  left:             0;
  background-color: #000;
  opacity:          0.7;
  position:         fixed;
}

.lightboxCenter {
  position:         fixed;
  height:           400px;
  width:            600px;
  top:              50%;
  left:             50%;
  margin-top:       -200px;
  margin-left:      -300px;
  border-radius:    10px;
  background-color: black;
}

.closeLightbox {
  float:           right;
  margin-right:    20px;
  color:           #d3d3d3;
  font-size:       60px;
  text-decoration: none;
  font-family:     sans-serif;
}

4 个答案:

答案 0 :(得分:0)

将你的css更改为

.lightboxBackground {
width:100%;
height:100%;
top:0;
left:0;
background-color:#000;
opacity:.7;
position:fixed;
}

.lightboxCenter {
position:fixed;
height: calc(100% - 200px);
width: calc(100% - 200px);
top:100px;
left:100px;
margin-top:0;
margin-left:0px;
border-radius:10px;
background-color: black;
}

.closeLightbox {
float:right;
margin-right:20px;
color:#d3d3d3;
font-size:60px;
text-decoration:none;
font-family:sans-serif;
}

现场演示:https://jsfiddle.net/36jkh1hj/1/

答案 1 :(得分:0)

我将您的.lightboxCenter更改为此jsFiddle):

.lightboxCenter {
    position:fixed;
    height:50%;
    width:50%;
    top:50%;
    left:50%;
    transform: translate(-50%, -50%);
    border-radius:10px;
    background-color: black;
}

希望这能帮到你!

答案 2 :(得分:0)

Here's a working JSFiddle

只需将您的CSS更改为:

.lightboxCenter {
    /* - no need for these:
    position:fixed;
    top:50%;
    left:50%;*/

    /*height:400px; - this won't allow your box to resize*/
    height: 50vh; /*change this to whatever size you desire*/

    /*width:600px; - this won't allow your box to resize*/
    width: 50vw; /*change this to whatever size you desire*/

    /*margin-top:-200px;
    margin-left:-300px;*/
    margin: 10% auto; /* - to make sure the box is always centered*/

    border-radius:10px;
    background-color: black;
    /*added css:*/
    display: block;
}

答案 3 :(得分:0)

让我们看一个如何做到这一点的例子:
https://jsfiddle.net/rcheruti/36jkh1hj/3/

需要对代码进行一些更改才能获得此行为:

1: div lightbox的所有部分内的群组。在exmaple中,我创建了一个lightbox类,其中包含BackgroundCenterclose标记。这对于更好地控制元素很重要,使用此结构,您可以在z-index中使用CSS使X按钮保持在其他元素之上(仅限于同一DOM树) )。

2:width的{​​{1}}和height设置为Center,并使用100%和{{1限制你想要成为最大值的大小。有了它,你将获得你想要的效果。如果这对您不起作用,那么我认为我们需要讨论max-width来解决这个问题。

3:您可以将max-height元素设置为media querysCenter上的50%。这两个属性是根据父相对元素计算的(在示例中,由于left CSS属性,它将是top元素)
有了这个位置是错误的,但我们用.lightbox来纠正这个问题。根据自身元素的大小计算变换。这会将元素定位在屏幕的中心。

4:请注意,position: fixed按钮的属性也需要更改。现在按钮为transform: translate(-50%, -50%)并且close已定位。

一个不同的解决方案是不使用inline-block宽度和高度,但要使用absolute来设置特定屏幕尺寸的高度和宽度,常见的是将宽度设置为max-以下一些尺寸的屏幕。