我如何用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>
当前回答
一个非常简单的和跨浏览器的答案到水平中心是将这个规则应用到母元素:
.parentBox {
display: flex;
justify-content: center
}
其他回答
CSS 3的盒子相匹配属性
#outer {
width: 100%;
height: 100%;
display: box;
box-orient: horizontal;
box-pack: center;
box-align: center;
}
可以使用中心标签为方便
<div id="outer">
<center>
<div id="inner">Foo foo</div>
</center>
</div>
我最近发现的一件好事,混合了线高度+垂直平行和50%左线技巧的使用,你可以在另一个动态尺寸的盒子内集中一个动态尺寸的盒子,在水平和垂直,使用纯粹的CSS。
请注意,您必须使用在现代浏览器 + Internet Explorer 8 中测试的 spans(和 inline-block)。
<h1>Center dynamic box using only css test</h1>
<div class="container">
<div class="center">
<div class="center-container">
<span class="dyn-box">
<div class="dyn-head">This is a head</div>
<div class="dyn-body">
This is a body<br />
Content<br />
Content<br />
Content<br />
Content<br />
</div>
</span>
</div>
</div>
</div>
CSS:
.container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
overflow: hidden;
}
.center {
position: absolute;
left: 50%;
top: 50%;
}
.center-container {
position: absolute;
left: -2500px;
top: -2500px;
width: 5000px;
height: 5000px;
line-height: 5000px;
text-align: center;
overflow: hidden;
}
.dyn-box {
display: inline-block;
vertical-align: middle;
line-height: 100%;
/* Purely asthetic below this point */
background: #808080;
padding: 13px;
border-radius: 11px;
font-family: arial;
}
.dyn-head {
background: red;
color: white;
min-width: 300px;
padding: 20px;
font-size: 23px;
}
.dyn-body {
padding: 10px;
background: white;
color: red;
}
请参见这里的例子
试着和周围玩
margin: 0 auto;
如果你也想集中你的文本,试着使用:
text-align: center;
您可以使用一行代码,仅仅是文本同步:中心。
下面是一个例子:
<div id="outer" style="width:100%"> <div id="inner"><button>hello</button></div> </div>