说我有HTML作为
<div class="page">
<div class="header"></div>
<div class="content">
<div class="foo">
<div>I want to be center of content</div>
</div>
</div>
<div class="footer"></div>
</div>
CSS
html, body {
height: 100%;
}
body {
margin: 0;
}
.page {
height: 100%;
display: flex;
flex-direction: column;
}
.header {
flex-shrink: 0;
background-color: green;
height: 50px;
}
.content {
flex-grow: 1;
}
.footer {
flex-shrink: 0;
background-color: steelblue;
height: 150px;
}
.foo {
display: flex;
justify-content: center;
align-items: center;
}
https://codepen.io/rrag/pen/PRmOYe
我在页面底部实现了粘性页脚
使用flex-grow
但导致内容高度未知
如何在content
的中间居中?
是否可以使用flexbox或者可能是另一种方法?
答案 0 :(得分:1)
你几乎有正确的想法!您不必在.foo
(display: flex;
,justify-content: center
;和align-items: center;
)上设置垂直居中规则,而只需在父.content
上设置它们。
可以在以下内容中看到这一点(点击Run snippet
然后点击Full page
即可看到此效果):
html,
body {
height: 100%;
}
body {
margin: 0;
}
.page {
height: 100%;
display: flex;
flex-direction: column;
}
.header {
flex-shrink: 0;
background-color: green;
height: 50px;
}
.content {
flex-grow: 1;
display: flex;
justify-content: center;
align-items: center;
}
.footer {
flex-shrink: 0;
background-color: steelblue;
height: 150px;
}
&#13;
<div class="page">
<div class="header"></div>
<div class="content">
<div class="foo">
<div>I want to be center of content</div>
</div>
</div>
<div class="footer"></div>
</div>
&#13;
这也可以看作 on CodePen 。