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

我有一个 div,它将有这样的 CSS:

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

现在,我怎么才能让这个 Div 居中呢?我可以使用 margin-left: -450px; left: 50%;,但是这只有当屏幕大于900像素时才能正常工作。在此之后(当窗口小于900像素时) ,它将不再居中。

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

159219 次浏览
<div id="container">
<div id="some_kind_of_popup">
center me
</div>
</div>

You'd need to wrap it in a container. here's the 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;
}

You can center a fixed or absolute positioned element setting right and left to 0, and then margin-left & margin-right to auto as if you were centering a static positioned element.

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

See this example working on this fiddle.

Here's another method if you can safely use CSS3's transform property:

.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%);
}

...or if you want both horizontal AND vertical centering:

.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%);
}

This works regardless of the size of its contents

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

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

This approach will not limit element's width when using margins in flexbox

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

Also for centering it vertically

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