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

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

当前回答

中心一个Div在一个Div

.outer { 显示: -webkit-flex; 显示: flex; //-webkit-justify-content: center; //justify-content: center; //align-items: center; width: 100%; height: 100px; background-color: lightgrey; }.inner { 背景颜色: cornflowerblue; padding: 2rem; margin: auto; //align-self: center; } <div class="outer"> <div class="inner"

其他回答

它不能集中,如果你不给它一个宽度,否则,它将采取,默认情况下,整个水平空间。

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

请参见这里的例子

这就是你想要的最短的方式。

JSFIDDLE

#outer {
  margin - top: 100 px;
  height: 500 px; /* you can set whatever you want */
  border: 1 px solid# ccc;
}

#inner {
  border: 1 px solid# f00;
  position: relative;
  top: 50 % ;
  transform: translateY(-50 % );
}

使用:

#outerDiv { 宽度: 500px; } #innerDiv { 宽度: 200px; 边缘: 0 auto; } <div id="outerDiv"> <div id="innerDiv"> 内部内容</div> </div>

中心:自动宽度边界

这个盒子是垂直集中,通过将其右边和左边边界的宽度设置为“自动”。 这是实现垂直集中CSS的最佳方式,并且在大多数使用CSS2支持的浏览器中非常好。 不幸的是,Internet Explorer 5/Windows不响应这种方法 - 该浏览器的缺点,而不是技术。

Internet Explorer 5/Windows 不正确地应用CSS“文本平衡”属性到区块级元素。 声明“文本平衡:中心”为包含区块级元素(通常是BODY元素)的垂直集中在Internet Explorer 5/Windows中的框架。

body {
    margin: 50px 0px;
    padding: 0px;
    text-align: center;
}

#Content {
    width: 500px;
    margin: 0px auto;
    text-align: left;
    padding: 15px;
    border: 1px dashed #333;
    background-color: #EEE;
}

http://bluerobot.com/web/css/center1.html