问题描述
我有一个div,会有这个CSS:
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;
}
现在,我如何使这个div居中?我可以使用 margin-left:-450px; left:50%;
,但这只会在屏幕大于900像素时才能使用。之后(当窗口
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.
我当然可以用某种js做这个,但是有一个更正确的这样做的CSS?
I can of course do this with some kind of js, but is there a "more correct" of doing this with CSS?
推荐答案
您可以将固定
绝对定位元素设置右
和左
到 code>,然后
margin-left
& margin-right
到 auto
,就好像你以 static
定位元素。
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%;
}
这篇关于中心固定div动态宽度(CSS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!