我如何用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 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 的老式同步的老式浏览器,这里是一个很好的地方去看。
其他回答
您可以使用链接 https://plnkr.co/edit/MQD5QHJe5oUVKEvHCz8p?p=preview
.outer{
display: table;
width: 100%;
height: 100%;
}
.inner {
vertical-align: middle;
}
参考 https://v4-alpha.getbootstrap.com/例子/覆盖/
中心一个元素,不需要动态高度和宽度的旋转器/父母
没有副作用:它不会限制一个集中元素的宽度低于视门宽度,当使用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 定义内容属性
它将Flexbox元件调整到容器的中心:
#outer {
display: flex;
justify-content: center;
}
只需将此 CSS 内容添加到您的 CSS 文件中,它将自动集中内容。
垂直调整到CSS中中心:
#outer {
display: flex;
justify-content: center;
}
垂直 + 垂直到中心在 CSS 中:
#outer {
display: flex;
justify-content: center;
align-items: center;
}
可以用很多方法来做到这一点,很多男孩/男孩的答案是正确的,并且工作得很好,我会给一个更不同的模式。
在HTML文件中
<div id="outer">
<div id="inner">Foo foo</div>
</div>
在 CSS 文件中
#outer{
width: 100%;
}
#inner{
margin: auto;
}