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

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

当前回答

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



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

其他回答

HTML:

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

CSS:

#outer{
  width: 500px;
  background-color: #000;
  height: 500px
}
#inner{
  background-color: #333;
  margin: 0 auto;
  width: 50%;
  height: 250px;
}

菲德尔

而不是多种包装和/或自动边缘,这个简单的解决方案对我来说工作:

<div style="top: 50%; left: 50%;
    height: 100px; width: 100px;
    margin-top: -50px; margin-left: -50px;
    background: url('lib/loading.gif') no-repeat center #fff;
    text-align: center;
    position: fixed; z-index: 9002;">Loading...</div>

它将Div放在视图(垂直和水平)的中心,尺寸和调整尺寸,中心背景图像(垂直和水平),中心文本(水平),并保持Div在视图和内容的顶部。

有一个选择,我发现:

每个人都说要使用:

margin: auto 0;

但还有另一个选项. 设置此属性为父母 div. 它在任何时候都完美工作:

text-align: center;

看,孩子去中心。

最后,为您提供CSS:

#outer{
     text-align: center;
     display: block; /* Or inline-block - base on your need */
}

#inner
{
     position: relative;
     margin: 0 auto; /* It is good to be */
}

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

垂直调整到CSS中中心:

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

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

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

专注于水平

演示:


以垂直和垂直为中心

在我的经验中,将盒子垂直和水平中心的最佳方式是使用额外的容器,并应用以下属性:

外部容器:

内部容器:

内容盒子:

.outer 容器 { 显示: 表; 宽度: 100%; 高度: 120px; 背景: #CCC; }. 内部容器 { 显示: 表 细胞; 垂直平面: 中间; 文本平面: 中间; }.centered 内容 { 显示: inline-block; 背景: #FFF; padding: 20px; 边界: 1px 固体 #000; } <div class="outer-container"> <div class="inter-container"> <div class="centered-content">

再看这个Fiddle吧!