我如何用CSS垂直集中一个 <div> 在另一个 <div> 中?

<div id="outer">
  <div id="inner">Foo foo</div>
</div>

当前回答

我知道我稍晚回答这个问题,我没有打扰阅读每一个答案,所以这可能是一个重复。

inner { width: 50%; background-color: Khaki; margin: 0 auto; }

其他回答

注意:我分享这个代码,因为谷歌带我到这个 Stack Overflow 解决方案,除了隐藏的元素没有任何宽度,直到它们显示后才可以重新测量/集中。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="inner" style="display:none;"> <form action=""> <table id="innerTable"> <tr><td> 姓名:</td><input type="text"></td> <tr><td> 电子邮件:</td><td><input type="text"></td>

我最近发现的一件好事,混合了线高度+垂直平行和50%左线技巧的使用,你可以在另一个动态尺寸的盒子内集中一个动态尺寸的盒子,在水平和垂直,使用纯粹的CSS。

请注意,您必须使用在现代浏览器 + Internet Explorer 8 中测试的 spans(和 inline-block)。

<h1>Center dynamic box using only css test</h1>
<div class="container">
  <div class="center">
    <div class="center-container">
      <span class="dyn-box">
        <div class="dyn-head">This is a head</div>
        <div class="dyn-body">
          This is a body<br />
          Content<br />
          Content<br />
          Content<br />
          Content<br />
        </div>
      </span>
    </div>
  </div>
</div>

CSS:

.container {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  overflow: hidden;
}

.center {
  position: absolute;
  left: 50%;
  top: 50%;
}

.center-container {
  position: absolute;
  left: -2500px;
  top: -2500px;
  width: 5000px;
  height: 5000px;
  line-height: 5000px;
  text-align: center;
  overflow: hidden;
}

.dyn-box {
  display: inline-block;
  vertical-align: middle;
  line-height: 100%;
  /* Purely asthetic below this point */
  background: #808080;
  padding: 13px;
  border-radius: 11px;
  font-family: arial;
}

.dyn-head {
  background: red;
  color: white;
  min-width: 300px;
  padding: 20px;
  font-size: 23px;
}

.dyn-body {
  padding: 10px;
  background: white;
  color: red;
}

请参见这里的例子

#inner {
    width: 50%;
    margin: 0 auto;
}

另一个解决方案,而无需为其中一个元素设置宽度,是使用CSS 3转换属性。

#outer {
  position: relative;
}

#inner {
  position: absolute;
  left: 50%;

  transform: translateX(-50%);
}

技巧是,翻译X(-50%)将#内部元素置于其自己的宽度的左侧50%。

這裡有一個顯示水平和垂直調整的Fiddle。

更多信息可在Mozilla Developer Network上找到。

给内部 div 一些宽度,并添加 margin:0 auto; 在 CSS 属性中。