94

I have a div that will have this CSS:

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

Now, how can i make this div centered? I can use margin-left: -450px; left: 50%; but this will only work when the screen is > 900 pixels. After that (when the window is < 900 pixels), it will no longer be centered.

I can of course do this with some kind of js, but is there a "more correct" of doing this with CSS?

4

5 回答 5

235

您可以将一个fixedabsolute定位的元素设置rightleftto居中0,然后margin-left& margin-righttoauto就好像您将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%;
}

请参阅使用此小提琴的此示例。

于 2013-06-12T15:55:51.053 回答
58

如果您可以安全地使用 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%);
}
于 2015-07-01T23:18:01.777 回答
8
<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;  
}
于 2013-06-12T15:38:43.943 回答
8

无论其内容的大小如何,这都有效

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

于 2018-02-01T10:36:07.177 回答
1

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

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

也用于垂直居中

top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
于 2021-01-13T01:46:44.800 回答