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

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

当前回答

它也可以用绝对定位来垂直和垂直集中,如下:

#outer{
    position: relative;
}

#inner{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%)
}

其他回答

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

例如:

HTML

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

CSS:

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

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

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

<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在视图和内容的顶部。

它是如此简单。

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

CSS

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

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

垂直调整到CSS中中心:

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

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

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

使用:

<style>
  #outer{
    text-align: center;
    width: 100%;
  }
  #inner{
    text-align: center;
  }
</style>