我如何用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 class="outer">
<div class="inner">
Foo foo
</div>
</div>
CSS 代码
.outer{
width: 100%;
height: 300px;
background: yellow;
}
.inner{
width: 30%;
height: 200px;
margin: auto;
background: red;
text-align: center
}
查看我的 CodePen 链接: http://codepen.io/feizel/pen/QdJJrK
此分類上一篇
其他回答
而不是多种包装和/或自动边缘,这个简单的解决方案对我来说工作:
<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在视图和内容的顶部。
一些海报已经提到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 的老式同步的老式浏览器,这里是一个很好的地方去看。
最好的方法是使用CSS3。
旧盒子模型(重定向)
显示:盒子和其属性盒子包、盒子平行、盒子东方、盒子方向等已被 flexbox 替换,虽然它们可能仍然工作,但不建议在生产中使用。
#outer { 宽度: 100%; /* Firefox */ 显示: -moz-box; -moz-box-pack:中心; -moz-box-align:中心; /* Safari 和 Chrome */ 显示: -webkit-box; -webkit-box-pack:中心; -webkit-box-align:中心; /* W3C */ 显示: 盒子; 盒子包:中心; 盒子包:中心; } #inner { 宽度: 50%; } <div id="outer"> <div id="inner">Foo foo</div> </div>
根据您的可用性,您也可以使用盒子方向、盒子灵活、盒子方向特性。
现代盒子模型与Flexbox
#outer {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
阅读更多关于专注于儿童元素
链接2 链接3 链接4
这解释了为什么盒子模型是最好的方法:
為什麼W3C盒子模型被認為更好?
我通常的方式是使用绝对的位置:
#inner{
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
}
外部迪夫不需要任何额外的属性来工作。
您可以使用 CSS Flexbox。
#inner {
display: flex;
justify-content: center;
}
您可以在此链接中了解更多信息: https://css-tricks.com/snippets/css/a-guide-to-flexbox/