我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。

我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。

.center {
  left: 50%;
  bottom: 5px;
}

我怎样才能做到这一点?


当前回答

HTML格式:

<div class="wrapper">
    <div class="inner">
        content
    </div>
</div>

CSS:

.wrapper {
    position: relative;

    width: 200px;
    height: 200px;

    background: #ddd;
}

.inner {
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;
    margin: auto;

    width: 100px;
    height: 100px;

    background: #ccc;
}

这里还有更多的例子。

其他回答

如果需要水平和垂直居中:

left: 50%;
top: 50%;
transform: translate(-50%, -50%);

我想补充一下bobince的回答:

<body>
    <div style="position: absolute; left: 50%;">
        <div style="position: relative; left: -50%; border: dotted red 1px;">
            I am some centered shrink-to-fit content! <br />
            tum te tum
        </div>
    </div>
</body>

改进:///这使得水平滚动条不会在居中的div中出现大元素。

<body>
    <div style="width:100%; position: absolute; overflow:hidden;">
        <div style="position:fixed; left: 50%;">
            <div style="position: relative; left: -50%; border: dotted red 1px;">
                I am some centered shrink-to-fit content! <br />
                tum te tum
            </div>
        </div>
    </div>
</body>

据我所知,对于未知的宽度,这是不可能实现的。

如果这在您的场景中有效,您可以绝对定位一个100%宽度和高度的不可见元素,并使用margin:auto和可能的垂直对齐将元素居中。否则,您将需要JavaScript来执行此操作。

我使用了类似的解决方案:

#styleName {
    position: absolute;
    margin-left: -"X"px;
}

其中“X”是要显示的div宽度的一半。它适用于所有浏览器。

HTML格式:

<div id='parent'>
  <div id='child'></div>
</div>

CSS:

#parent {
  display: table;
}
#child {
  display: table-cell;
  vertical-align: middle;
}

我知道我已经给出了答案,我之前的答案和其他人的答案都很好。但我在过去使用过这个,它在某些浏览器和某些情况下效果更好。所以我想我也会给出这个答案。我没有“编辑”我之前的答案并添加它,因为我觉得这是一个完全独立的答案,我提供的两个答案并不相关。