当高度未知时,使用flexbox垂直居中时出现问题 [英] Issue when centering vertically with flexbox when heights are unknown
本文介绍了当高度未知时,使用flexbox垂直居中时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的布局有一个容器 flex-container 和一个孩子。
HTML:
< div class = >
< div> text< / div>
< / div>
容器和子项有未知高度。目标是:
- 如果孩子的高度低于容器的高度,它会水平和垂直居中。
- 如果孩子的高度大于容器的高度,它会调整到顶部和底部,我们可以滚动。
计划:
使用flexbox定位元素的最快方法如下:
CSS:
.flex-container
{
display:flex;
align-items:center; // vertical
justify-content:center; // horizontal
width:100%;
height:300px; // for example purposes
overflow-y:scroll;
background:#2a4;
}
.flex-container> div
{
background:#E77E23;
width:400px;
}
Codepen:
My layout have a container flex-container and a child.
HTML:
<div class="flex-container">
<div>text</div>
</div>
The container and the child have an unknown height. And the goal is:
- If the child has a lower height than the container, it appears centered horizontally and vertically.
- If the child has a greater height than the container, it adjusts to the top and the bottom and we can do scroll.
Scheme:
The fastest way for centering a element with flexbox is the follow:
CSS:
.flex-container
{
display: flex;
align-items: center; // vertical
justify-content: center; // horizontal
width: 100%;
height: 300px; // for example purposes
overflow-y: scroll;
background: #2a4;
}
.flex-container > div
{
background: #E77E23;
width: 400px;
}
Codepen: http://www.codepen.io/ces/pen/slicw
But, if the container's child have a greater height, the child is not shown correctly. The child appears cutted (only the top part).
Codepen: http://www.codepen.io/ces/pen/sGtfK
Scheme:
Is there a way for resolve this issue?
解决方案
I found the solution:
.flex-container
{
display: flex; // only
overflow-y: scroll;
}
.flex-container > div
{
margin: auto; // horizontal and vertical align
}
Codepen: http://codepen.io/ces/pen/Idklh
这篇关于当高度未知时,使用flexbox垂直居中时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文