中心固定div动态宽度(CSS) [英] Center fixed div with dynamic width (CSS)

查看:158
本文介绍了中心固定div动态宽度(CSS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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像素时才能使用。之后(当窗口<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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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