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

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

当前回答

这肯定会把你的内部都集中在水平上和垂直上,这也适用于所有浏览器,我只是添加了额外的风格,只是为了显示它是如何集中的。

#outer {背景:黑色;位置:相对;宽:150px;高度:150px; } 内部 {背景:白色;位置:绝对;左:50%;顶部:50%;转换:翻译(50%,-50%); -webkit-转换:翻译(50%,-50%); -moz-转换:翻译(50%,-50%); -o-转换:翻译(50%,-50%); } <div id="outer"> <div id="inner">Foo foo</div> </div>

但是,當然,如果你只想它垂直調整,這可能會幫助你。

其他回答

我使用Flexbox或CSS网络

Flexbox #outer{ 显示: flex;正当内容:中心; } CSS 网络 #outer { 显示: 内线网络; 网络模板线: 100px 100px; 网络模板列: 100px 100px; 网络错误: 3px; }

你可以以多种方式解决这个问题。

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

请参见这里的例子

首先:你需要给第二 Div 一个宽度:

例如:

HTML

<div id="outter">
    <div id="inner"Centered content">
    </div
</div>

CSS:

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

请注意,如果你不给它一个宽度,它将采取整个线的宽度。

CSS 3的盒子相匹配属性

#outer {
    width: 100%;
    height: 100%;
    display: box;
    box-orient: horizontal;
    box-pack: center;
    box-align: center;
}

#inter { 边界: 0.05em 固体黑色; } #outer { 边界: 0.05em 固体红色; 宽度:100%; 显示: flex; justify-content: center; } <div id="outer"> <div id="inner"> Foo foo</div> </div>


其他解决方案

您可以将此 CSS 应用到内部 <div>:

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

当然,你不需要设置宽度为50%,任何宽度低于含有<div>的将工作。

如果您正在针对 Internet Explorer 8 (及以后),可能更好地拥有此相反:

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

它将使内部元素的中心垂直,它工作而不设置特定的宽度。

工作例子在这里: