我如何用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>
当前回答
中心一个元素,不需要动态高度和宽度的旋转器/父母
没有副作用:它不会限制一个集中元素的宽度低于视门宽度,当使用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 内容添加到您的 CSS 文件中,它将自动集中内容。
垂直调整到CSS中中心:
#outer {
display: flex;
justify-content: center;
}
垂直 + 垂直到中心在 CSS 中:
#outer {
display: flex;
justify-content: center;
align-items: center;
}
我已经应用了内线风格到内部 div. 使用此一个:
<div id="outer" style="width:100%">
<div id="inner" style="display:table;margin:0 auto;">Foo foo</div>
</div>
另一个解决方案,而无需为其中一个元素设置宽度,是使用CSS 3转换属性。
#outer {
position: relative;
}
#inner {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
技巧是,翻译X(-50%)将#内部元素置于其自己的宽度的左侧50%。
這裡有一個顯示水平和垂直調整的Fiddle。
更多信息可在Mozilla Developer Network上找到。
我很抱歉,但这个90年代的婴儿只是为我工作:
<div id="outer">
<center>Foo foo</center>
</div>
我要为这个罪而去地狱吗?
一些海报已经提到CSS 3的中心方式使用显示:盒子。
这个合成是过时的,不应该再使用。
因此,仅仅是为了完整性,这里是使用灵活盒子布局模块在CSS 3中集中最新的方式。
所以,如果你有简单的标签如:
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
...你想把你的物品集中在盒子内,这里是你需要的父母元素(.box):
.box {
display: flex;
flex-wrap: wrap; /* Optional. only if you want the items to wrap */
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
.box { 显示: flex; flex-wrap: wrap; /* 可选. 只有如果您想要的物品将 wrap */ 定义内容: 中心; /* 为水平调整 */ 定义项目: 中心; /* 为垂直调整 */ } * { 边界: 0; 粘贴: 0; } html, 身体 { 高度: 100%; }.box { 高度: 200px; 显示: flex; flex-wrap: 定义内容: 中心; 定义项目: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容: 定义内容
如果您需要支持使用 flexbox 的老式同步的老式浏览器,这里是一个很好的地方去看。