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

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

当前回答

我最近发现的一件好事,混合了线高度+垂直平行和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;
}

请参见这里的例子

其他回答

一个非常简单的和跨浏览器的答案到水平中心是将这个规则应用到母元素:

.parentBox {
    display: flex;
    justify-content: center
}

我在各个项目中使用的最好是

<div class="outer">
    <div class="inner"></div>
</div>
.outer{
  width: 500px;
  height: 500px;
  position: relative;
  background: yellow;
}
.inner{
  width: 100px;
  height: 100px;
  background:red;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

Fiddle 链接

#outer{
  display: flex;
  width: 100%;
  height: 200px;
  justify-content:center;
  align-items:center;
}

回归2022

这是一个非常古老的问题,所以我只是试图报告今天的情况:

CSS 网络和 flexbox 是您对中心、水平或垂直的最佳选项; margin:auto 方法工作得好,如果内部内容不是一个盒子(内线区块是好的); margin 50% 与 transform:translateX(50%) 是粗糙的力量,但工作得好; 与绝对的位置和 translateX/Y 也适用于水平和垂直的中心,许多对话使用它,扩展高度

这就是2022年的样子,我希望我们永远不会需要更多的网和 flexbox。

CSS 定义内容属性

它将Flexbox元件调整到容器的中心:

#outer {
    display: flex;
    justify-content: center;
}