中心固定div与动态宽度(CSS)

时间:2013-06-12 15:28:54

标签: css html center

我有一个将拥有此CSS的div:

#some_kind_of_popup
{
    position: fixed;
    top: 100px;
    min-height: 300px;
    width: 90%;
    max-width: 900px;
}

现在,我怎样才能使这个div居中?我可以使用margin-left: -450px; left: 50%;但这仅在屏幕为&gt;时才有效900像素。之后(当窗口<900像素时),它将不再居中。

我当然可以用某种js来做这件事,但是用CSS做“更正确”吗?

5 个答案:

答案 0 :(得分:202)

您可以将fixedabsolute定位元素设置rightleft置于0,然后margin-left&amp; margin-rightauto,好像您将static定位元素居中一样。

#example {
    position: fixed;
    /* center the element */
    right: 0;
    left: 0;
    margin-right: auto;
    margin-left: auto;
    /* give it dimensions */
    min-height: 10em;
    width: 90%;
}

请参阅此示例工作on this fiddle

答案 1 :(得分:43)

如果您可以安全地使用CSS3的transform属性,那么这是另一种方法:

.fixed-horizontal-center
{
    position: fixed;
    top: 100px; /* or whatever top you need */
    left: 50%;
    width: auto;
    -webkit-transform: translateX(-50%);
    -moz-transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    -o-transform: translateX(-50%);
    transform: translateX(-50%);
}

...或者如果你想要水平和垂直居中:

.fixed-center
{
    position: fixed;
    top: 50%;
    left: 50%;
    width: auto;
    height: auto;
    -webkit-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    -o-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}

答案 2 :(得分:6)

<div id="container">
    <div id="some_kind_of_popup">
        center me
    </div>
</div>

您需要将其包装在容器中。这是css

#container{
    position: fixed;
    top: 100px;
    width: 100%;
    text-align: center;
}
#some_kind_of_popup{
    display:inline-block;
    width: 90%;
    max-width: 900px;  
    min-height: 300px;  
}

答案 3 :(得分:1)

无论内容大小如何,都可以使用

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

来源:https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

答案 4 :(得分:1)

这种方法在 flexbox 中使用边距时不会限制元素的宽度

top: 0; left: 0;
transform: translate(calc(50vw - 50%));

也用于垂直居中

top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
相关问题