当高度未知时,使用柔性盒垂直居中时发出问题
我的布局有一个容器flex-container
和一个孩子。
HTML:
<div class="flex-container">
<div>text</div>
</div>
集装箱和孩子身高未知 。 目标是:
方案:
用flexbox对一个元素进行居中的最快方法如下:
.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;
}
<div class="flex-container">
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. </div>
</div>
我找到了解决方案:
.flex-container
{
display: flex; /* only */
overflow-y: scroll;
}
.flex-container > div
{
margin: auto; /* horizontal and vertical align */
}
html,body
{
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
.flex-container
{
display: flex;
width: 100%;
height: 100px; /* change height to 300px */
overflow-y: scroll;
background: #2a4;
}
.flex-container > div
{
padding: 1em 1.5em;
margin: auto;
background: #E77E23;
width: 400px;
}
<div class="flex-container">
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. </div>
</div>
添加align-self:flex-start;
到.flex-container > div
也可以解决这个问题。
请参阅:http://www.w3.org/TR/css-flexbox-1/#auto-margins
链接地址: http://www.djcxy.com/p/13253.html上一篇: Issue when centering vertically with flexbox when heights are unknown