我如何用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:
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
其他回答
而不是多种包装和/或自动边缘,这个简单的解决方案对我来说工作:
<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在视图和内容的顶部。
#outer { 显示: 网; justify- 内容: 中心; } <div id="outer"> <div id="inner">hello</div> </div> 在这里输入代码
如果你有一个父母的某种高度说,身体{高度: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 id="a">
<div id="b"></div>
</div>
CSS:
#a{
border: 1px solid red;
height: 120px;
width: 400px
}
#b{
border: 1px solid blue;
height: 90px;
width: 300px;
position: relative;
margin-left: auto;
margin-right: auto;
}
#outer { 宽度: 160px; padding: 5px; 边界风格: 固体; 边界宽度: 薄; 显示: 区块; } 内部 { 边界: 自动; 背景颜色: 光蓝; 边界风格: 固体; 边界宽度: 薄; 宽度: 80px; padding: 10px; 文本平衡: 中心; } <div id="outer"> <div id="inner">Foo foo</div> </div>