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

请参见这里的例子

其他回答

<div id="outer" style="width:100%;margin: 0 auto; text-align: center;"> <div id="inner">Foo foo</div> </div>

<html>

*{ margin: 0; padding: 0; } #outer{ 背景: 红色; 宽度: 100%; 高度: 100vh; 显示: flex; /*center 垂直*/ 正当内容: 中心; flex 方向: 列; /*center 垂直*/ 匹配元素: 中心; } #inner{ 宽度: 80%; 高度: 40px; 背景: g

如果你有一个父母的某种高度说,身体{高度:200px} 或如下有父母 div#outer 高度200px,然后添加CSS内容如下

HTML:

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

CSS:

#outer{
  display: flex;
  width: 100%;
  height: 200px;
}
#centered {
  margin: auto;
}

然后,儿童内容,说 div#中心内容,将垂直或垂直中间,不使用任何位置的CSS。

#centered {
  margin: 0px auto;
}

#outer{
  display: flex;
  width: 100%;
  height: 200px;
}
#centered {
  margin: auto;
}

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

演示: https://jsfiddle.net/jinny/p3x5jb81/5/

只添加一个界限显示内部 div 不是 100% 默认:

#outer{ 显示: flex; 宽度: 100%; 高度: 200px; 边界: 1px 固体 #000000; } #centered { 边界: auto; 边界: 1px 固体 #000000; } <div id="outer"> <div id="centered"> Foo foo</div> </div>

DEMO: http://jsfiddle.net/jinny/p3x5jb81/9

可以用很多方法来做到这一点,很多男孩/男孩的答案是正确的,并且工作得很好,我会给一个更不同的模式。

在HTML文件中

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

在 CSS 文件中

#outer{
  width: 100%;
}

#inner{
  margin: auto;
}

只需将此 CSS 内容添加到您的 CSS 文件中,它将自动集中内容。

垂直调整到CSS中中心:

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

垂直 + 垂直到中心在 CSS 中:

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