我如何用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>
当前回答
只需将此 CSS 内容添加到您的 CSS 文件中,它将自动集中内容。
垂直调整到CSS中中心:
#outer {
display: flex;
justify-content: center;
}
垂直 + 垂直到中心在 CSS 中:
#outer {
display: flex;
justify-content: center;
align-items: center;
}
其他回答
试试这:
<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;
}
中心一个元素,不需要动态高度和宽度的旋转器/父母
没有副作用:它不会限制一个集中元素的宽度低于视门宽度,当使用Flexbox中的边缘在一个集中元素内
position: fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%));
垂直 + 垂直中心,如果其高度与宽度相同:
position: fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
CSS
#inner {
display: table;
margin: 0 auto;
}
HTML
<div id="outer" style="width:100%">
<div id="inner">Foo foo</div>
</div>
#inter { 边界: 0.05em 固体黑色; } #outer { 边界: 0.05em 固体红色; 宽度:100%; 显示: flex; justify-content: center; } <div id="outer"> <div id="inner"> Foo foo</div> </div>
其他解决方案
您可以将此 CSS 应用到内部 <div>:
#inner {
width: 50%;
margin: 0 auto;
}
当然,你不需要设置宽度为50%,任何宽度低于含有<div>的将工作。
如果您正在针对 Internet Explorer 8 (及以后),可能更好地拥有此相反:
#inner {
display: table;
margin: 0 auto;
}
它将使内部元素的中心垂直,它工作而不设置特定的宽度。
工作例子在这里:
是的,这是一个短暂而干净的水平调整代码。
.classname {
display: box;
margin: 0 auto;
width: 500px /* Width set as per your requirement. */;
}