当高度未知时,用flexbox垂直居中时发出问题
我的布局有一个容器flex-container
和一个孩子。
HTML:
<div class="flex-container"> <div>text</div> </div>
容器和孩子有一个未知的高度 。 目标是:
- 如果孩子的身高低于容器的高度,则会出现水平和垂直居中。
- 如果孩子的身高高于容器的高度,则调整到顶部和底部,我们可以做滚动。
scheme:
以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>
Codepen: http : //www.codepen.io/ces/pen/slicw
但是,如果集装箱的小孩身高更高,那么孩子就没有正确显示。 孩子出现割伤(只有顶部)。
html,body { height: 100%; width: 100%; padding: 0; margin: 0; } .flex-container { display: flex; align-items: center; // vertical justify-content: center; // horizontal width: 100%; height: 100px; 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>
Codepen: http : //www.codepen.io/ces/pen/sGtfK
scheme:
有没有办法解决这个问题?
我find了解决办法:
.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