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

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

当前回答

你可以以不同的方式做到这一点. 请参见下面的例子:

1. First Method
#outer {
   text-align: center;
   width: 100%;
}
#inner {
   display: inline-block;
}


2. Second method
#outer {
  position: relative;
  overflow: hidden;
}
.centered {
   position: absolute;
   left: 50%;
}

其他回答

#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;
}

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

工作例子在这里:

.outer { 背景颜色: rgb(230,230,255); 宽度: 100%; 高度: 50px; }.inner { 背景颜色: rgb(200,200,255); 宽度: 50%; 高度: 50px; 边界: 0 auto; } <div class="outer"> <div class="inner"> 边界 0 auto </div> </div>

#outer {postion: relative}
#inner {
    width: 100px; 
    height: 40px; 
    position: absolute;
    top: 50%;
    margin-top: -20px; /* Half of your height */
}

它是如此简单。

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

CSS

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

这个方法也很好地工作:

div.container {
  display: flex;
  justify-content: center; /* For horizontal alignment */
  align-items: center;     /* For vertical alignment   */
}

对于内部<div>,唯一的条件是其高度和宽度不应大于其容器的高度。