我如何用CSS垂直集中一个 <div> 在另一个 <div> 中?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
我如何用CSS垂直集中一个 <div> 在另一个 <div> 中?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
当前回答
要在中间调整一个 div 中间的 div -
.outer{ 宽度: 300px; /* 例如 */ 高度: 300px; /* 例如 */ 背景: 红色; }.inner{ 位置: 相对; 顶部: 50%; 左: 50%; 转换: 翻译(-50%, -50%); 宽度: 200px; 高度: 200px; 背景: 黄色; } <body> <div class='outer'> <div class='inner'></div> </div> </body>
这将使中间的内部迪夫均匀,垂直和水平。
其他回答
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;
}
#outer { 显示: 网; justify- 内容: 中心; } <div id="outer"> <div id="inner">hello</div> </div> 在这里输入代码
如果你知道它的宽度,让我们说它是1200像素,去:
.container {
width:1200px;
margin-left: calc(50% - 600px);
}
因此,基本上它将添加50%的左边边,低于已知宽的一半。
如果你有一个父母的某种高度说,身体{高度:200px} 或如下有父母 div#outer 高度200px,然后添加CSS内容如下
HTML:
<div id="outer">
<div id="centered">Foo foo</div>
</div>
CSS:
#outer{
display: flex;
width: 100%;
height: 200px;
}
#centered {
margin: auto;
}
然后,儿童内容,说 div#中心内容,将垂直或垂直中间,不使用任何位置的CSS。
#centered {
margin: 0px auto;
}
或
#outer{
display: flex;
width: 100%;
height: 200px;
}
#centered {
margin: auto;
}
<div id="outer">
<div id="centered">Foo foo</div>
</div>
演示: https://jsfiddle.net/jinny/p3x5jb81/5/
只添加一个界限显示内部 div 不是 100% 默认:
#outer{ 显示: flex; 宽度: 100%; 高度: 200px; 边界: 1px 固体 #000000; } #centered { 边界: auto; 边界: 1px 固体 #000000; } <div id="outer"> <div id="centered"> Foo foo</div> </div>
DEMO: http://jsfiddle.net/jinny/p3x5jb81/9
您可以使用链接 https://plnkr.co/edit/MQD5QHJe5oUVKEvHCz8p?p=preview
.outer{
display: table;
width: 100%;
height: 100%;
}
.inner {
vertical-align: middle;
}
参考 https://v4-alpha.getbootstrap.com/例子/覆盖/