我如何用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>
当前回答
.outer {
text-align: center;
width: 100%
}
其他回答
与网
一个非常简单和现代的方式是使用显示器:网:
div { 边界: 1px dotted 灰色; } #outer { 显示: 网; 地点标题: 中心; 高度: 50px; /* 不需要 */ } <!DOCTYPE html> <html> <head> </head> <body> <div id="outer"> <div> Foo foo</div> </div> </body> </html>
中心一个Div在一个Div
.outer { 显示: -webkit-flex; 显示: flex; //-webkit-justify-content: center; //justify-content: center; //align-items: center; width: 100%; height: 100px; background-color: lightgrey; }.inner { 背景颜色: cornflowerblue; padding: 2rem; margin: auto; //align-self: center; } <div class="outer"> <div class="inner"
如果你有一个父母的某种高度说,身体{高度: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
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;
}
中心的主要属性是边界:自动和宽度:根据要求:
.DivCenter{
width: 50%;
margin: auto;
border: 3px solid #000;
padding: 10px;
}