简体   繁体   English

如何用css将叠加固定div定位到中心?

[英]How to position overlay fixed div to the center with css?

I have a div that appears once I have clicked some action to another element in the website. 一旦我点击某个动作到网站中的另一个元素,我就会出现一个div It is a fixed div that appears on top of all divs and the background is darkened. 它是一个固定的div ,出现在所有div的顶部,背景变暗。 I need to make sure that this div has been positioned to the center, and stays in the center even if the window is re-sized. 我需要确保这个div已经定位到中心,并且即使窗口重新调整大小也会保持在中心位置。

I have tried the left , margin-left:50% trick, but it's not doing the job. 我尝试了leftleft margin-left:50%技巧,但它没有完成这项工作。

Here's my code: 这是我的代码:

<div class="overlay-box">Some content</div>

CSS CSS

.overlay-box {
background-color:#fff;
        width:550px;
left:50%;
    margin-left:-275px;
position:fixed;
text-align:center;
border:1px solid #000;
}

It doesn't position at center, and upon resizing it has a bigger margin towards the left than the right. 它没有位于中心位置,并且在调整大小时,左侧比右侧有更大的余量。 How do I fix this? 我该如何解决? Is there a magic trick like margin:0px auto for fixed divs? 是否存在像margin:0px auto这样的魔术margin:0px auto固定div的margin:0px auto

I just Practiced before pasting here 我刚刚在这里粘贴之前练习过

.overlay-box {
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
    color: white; background: #666666; opacity: .8;
    z-index: 1000;
}

Put the div inside another div which is 100% width and text-align center. 将div放在另一个100%宽度和文本对齐中心的div中。 Also set .overlay-box {margin: auto} 同时设置.overlay-box {margin:auto}

.container-box {
   background-color:#000;
   width:100%;
   height: 100%;
   text-align:center;
}
.overlay-box {
   background-color:#fff;
   width:300px;
   margin: auto;
}


<div class="container-box">
  <div class="overlay-box">Some content</div>
</div>

Working JSFiddle: https://jsfiddle.net/5kkdaqe6/ 工作JSFiddle: https ://jsfiddle.net/5kkdaqe6/

You can set top, right, bottom, left to 0 and margin to auto to vertically and horizontally center align fixed div. 您可以将top,right,bottom,left设置为0,将margin设置为auto,垂直和水平居中对齐固定div。 But this will only work if you set the height of div using CSS. 但这只有在使用CSS设置div的高度时才有效。

.overlay-box {
    background-color: #fff;
    border: 1px solid #000;
    text-align:center;
    height: 200px;/*height needs to be set*/
    width: 550px;
    margin: auto;
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

If you can't set the height then consider using flex layout https://css-tricks.com/snippets/css/a-guide-to-flexbox/ 如果您无法设置高度,请考虑使用flex layout https://css-tricks.com/snippets/css/a-guide-to-flexbox/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM