我如何用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;
}

请参见这里的例子

其他回答

如果您不想设置固定宽,并且不需要额外的边界,则将显示器添加到您的元素中: inline-block。

你可以使用:

#element {
    display: table;
    margin: 0 auto;
}

我认为这将是一个解决方案:

#outer {
    position: absolute;
    left: 50%;
}

#inner {
    position: relative;
    left: -50%;
}

两个元素必须是相同的宽度,以便单独运作。

添加文本:中心;到 parent div

#outer {
    text-align: center;
}

HTTPS://jsfiddle.net/7qwxx9rs/

#outer > div {
    margin: auto;
    width: 100px;
}

HTTPS://jsfiddle.net/f8su1fLz/

我最近找到了一个方法:

#outer {
    position: absolute;
    left: 50%;
}

#inner {
    position: relative;
    left: -50%;
}

两个元素必须是相同的宽度,以便正常运作。

它是如此简单。

只需决定你想要给内部Div的宽度,然后使用下面的CSS。

CSS

.inner{
  width: 500px; /* Assumed width */
  margin: 0 auto;
}