如何使用CSS定位覆盖固定div到中心? [英] How to position overlay fixed div to the center with css?

查看:118
本文介绍了如何使用CSS定位覆盖固定div到中心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 div ,一旦我点击了某个动作到网站中的其他元素,就会出现。它是一个固定的 div ,它出现在所有div的顶部,并且背景变暗。我需要确保这个div已经定位到中心位置,并且即使窗口被重新调整大小也会保留在中间位置。



我试过了 left , margin-left:50%技巧,但它没有完成这项工作。



以下是我的代码:

 < div class =overlay-box>一些内容< DIV> 

CSS

  .overlay-box {
background-color:#fff;
width:550px;
剩下:50%;
margin-left:-275px;
位置:固定;
text-align:center;
border:1px solid#000;
}

它并不位于中心位置,在调整大小后它有更大的余量朝向左侧而不是右侧。我该如何解决?对于固定div,有没有像 margin:0px auto 这样的固定div的魔术?

解决方案

您可以将顶部,右侧,底部,左侧设置为0,并将边距设置为自动垂直和水平居中对齐固定格。但这只会在你使用CSS设置div的高度时才起作用。

$ over $ box $ {
background-颜色:#fff;
border:1px solid#000;
text-align:center;
height:200px; / *需要设置高度* /
width:550px;
margin:auto;
位置:固定;
top:0;
right:0;
bottom:0;
剩下:0;





$ b

如果你不能设置高度,那么可以考虑使用flex layout https://css-tricks.com/snippets/css/a-guide-to -flexbox /


I have a div that appears once I have clicked some action to another element in the website. It is a fixed div that appears on top of all divs and the background is darkened. 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.

I have tried the left, margin-left:50% trick, but it's not doing the job.

Here's my code:

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

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?

解决方案

You can set top, right, bottom, left to 0 and margin to auto to vertically and horizontally center align fixed div. But this will only work if you set the height of div using CSS.

.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/

这篇关于如何使用CSS定位覆盖固定div到中心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆