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

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

当前回答

div{
    width: 100px;
    height: 100px;
    margin: 0 auto;
}

通常情况下,如果您正在使用DIV静态方式。

如果你想要一个Div集中在Div是绝对的父母,这里是例子:

.parentdiv{
    position: relative;
    height: 500px;
}

.child_div{
   position: absolute;
   height: 200px;
   width: 500px;
   left: 0;
   right: 0;
   margin: 0 auto;
}

其他回答

<div id="outer" style="width:100%;margin: 0 auto; text-align: center;"> <div id="inner">Foo foo</div> </div>

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

设置宽度,并设置边缘向左和边缘向右到自动。 这是仅限于水平,但是. 如果你想要两种方式,你只会做这两种方式. 不要害怕尝试; 它不像你会打破任何东西。

与网

一个非常简单和现代的方式是使用显示器:网:

div { 边界: 1px dotted 灰色; } #outer { 显示: 网; 地点标题: 中心; 高度: 50px; /* 不需要 */ } <!DOCTYPE html> <html> <head> </head> <body> <div id="outer"> <div> Foo foo</div> </div> </body> </html>

CSS

#inner {
  display: table;
  margin: 0 auto; 
}

HTML

<div id="outer" style="width:100%">  
  <div id="inner">Foo foo</div>
</div>