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

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

当前回答

#outer{
  display: flex;
  width: 100%;
  height: 200px;
  justify-content:center;
  align-items:center;
}

其他回答

最简单的方式之一......

<!DOCTYPE html>
<html>
    <head>
        <style>
            #outer-div {
                width: 100%;
                text-align: center;
                background-color: #000
            }
            #inner-div {
                display: inline-block;
                margin: 0 auto;
                padding: 3px;
                background-color: #888
            }
        </style>
    </head>

    <body>
       <div id ="outer-div" width="100%">
           <div id ="inner-div"> I am a easy horizontally centered div.</div>
       <div>
    </body>
</html>
#outer {postion: relative}
#inner {
    width: 100px; 
    height: 40px; 
    position: absolute;
    top: 50%;
    margin-top: -20px; /* Half of your height */
}

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

例如:

HTML

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

CSS:

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

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

最好的方法是使用桌面细胞显示器(内部),即与显示表(外部)的Div之后,并为内部Div(与桌面细胞显示器)设置垂直调整,并在Div或页面中心的内部Div中使用的每个标签。

注意:您必须将指定的高度设置到外面

它是最好的方式你知道没有位置相对或绝对,你可以使用它在每个浏览器一样。

#outer{ 显示: 表; 高度: 100vh; 宽度: 100%; } #inner{ 显示: 表细胞; 垂直平衡: 中间; 文本平衡: 中心; } <div id="outer"> <div id="inner"> <h1> 设置内容中心 </h1> <div> hi 这是最适合您的项目中心 </div> </div> </div> </div>

此分類上一篇: Margin:0px auto:

此分類上一篇: <div id="outer" style="width:100%"> <div id="inner">Foo foo</div> </div>