如何将 <div> 居中并使其使用固定定位?

How to both center a <div> and have it use fixed positioning?

我的页面上有一个 div,其中包含一些文本,我希望它位于底部。我使用固定定位做到了这一点:

div#popup{
    position: fixed;
    bottom: 0;

但我也希望它居中。我试着给它一个 40% 的宽度和自动边距,但这不起作用(它不适用于上述代码的组合):

 div#popup{
    position: fixed;
    bottom: 0;
    width: 40%;
    margin-left: auto;
    margin- right: auto;

我怎样才能做到这一点?

谢谢。

如果您知道 div 的宽度,您可以使用负的 margin-left 作为水平位置(等于宽度的一半)。

div {
    position: fixed;
    bottom: 0;
    left: 50%;
    width: 40%;
    height: 30px;
    margin-left: -20%;
    background: blue;
}

JSFiddle

如果您不知道宽度,只需使用包装器和内联块:

HTML:

<section>
    <div>la-la-la</div>
</section>

CSS:

section {
    position: fixed;
    bottom: 0;

    width: 100%;

    text-align: center;
}

div {
    display: inline-block;
    border: 1px solid red;
    color: red;
}

JSFiddle

我鼓励您查看两个不错的教程(快速阅读):

http://www.barelyfitz.com/screencast/html-training/css/positioning http://learnlayout.com/position.html

我认为你需要这样描述职位:

div#popup{
    position: fixed;
    bottom: 0;
    right: 50%;
}

首先,你不应该使用固定定位来让你的页脚粘在底部。要让页脚贴在屏幕底部,请将所有 div 设置为相对,然后在内容和页脚。然后在您的内容上放置负高度的边距 div。完美运行。

要居中,使用 width auto 和 margin left and right auto 或者只使用 text-align center