我已经尝试了很多方法来将儿童元素作为绝对垂直中心的中心,但使用任何技术都无法取得成功. Here’s one example what I’ve tried: HTML(不能改变): div class="foo" h1blah blah/h1 pfoo/p pbar/p/div C
Here’s one example what I’ve tried:
HTML(不能改变):
<div class="foo">
<h1>blah blah</h1>
<p>foo</p>
<p>bar</p>
</div>
CSS:
.foo{
position: absolute;
top: 0;
bottom: 0;
background: yellow;
}
.foo:before{
content: "";
display: inline-block;
vertical-align: middle;
height: 100%;
}
请注意:我无法更改标记,即我无法用父div包装.foo,甚至不能用div包装.foo中的所有子项.
那么,我怎样才能将它们垂直居中于整个窗口?
您可以通过使用css flexbox布局来实现这一点:JSFiddle – DEMO
.foo {
position: absolute;
top: 0;
bottom: 0;
background: yellow;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
flex-wrap: wrap;
/* align-items: center; */
}
h1, p {
margin:0;
}
<div class="foo">
<h1>blah blah</h1>
<p>foo</p>
<p>bar</p>
</div>
