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

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

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

我怎样才能做到这一点?


当前回答

您可以将图像放置在一个div中,添加一个div id,并让该div的CSS具有文本align:center:

HTML格式:

<div id="intro_img">

    <img src="???" alt="???">

</div>

CSS:

#intro_img {
    text-align: center;
}

其他回答

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;
}

这里还有更多的例子。

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

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

我想补充一下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>

HTML格式:

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

CSS:

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

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

HTML

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

CSS

#parent {
  position: relative;
}
#centered-child {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto auto;
}

http://jsfiddle.net/f51rptfy/