繁体   English   中英

将一个项目垂直居中,将另一个与动态高度底部对齐(弹性框)

[英]Vertically center one item and bottom-align another with dynamic height (flexbox)

这是我多次遇到的问题,因此我想这一次将寻求一个明确的答案。 我想做的是,使一个元素垂直居中,同时让另一个元素充当“页脚”,并捕捉到同一容器的底部。 像这样:

在此处输入图片说明

问题在于页脚将具有动态高度。 预期的行为是,如果有足够的空间,则中间元素将保持垂直居中; 如果页脚太大而无法实现,则居中内容将向上移动,为页脚腾出空间。

我找到的最接近的解决方案是这个问题 但是,就像我看到的所有其他解决方案一样,它需要知道页脚的高度。

我有一种预感,这与flexbox是不可能的。 我最终得到的解决方案总是回到经典position: relative包装, position: absolute页脚上的position: absolute

如果您想看看我上次尝试的失败之处,这里有一个演示小提琴

 flex-container { display: flex; flex-direction: column; align-items: center; justify-content: center; border: 4px solid blue; height: 300px; width: 300px; } flex-container>flex-spacer { margin-top: auto; visibility: hidden; } flex-container>flex-item { display: flex; } flex-container>flex-footer { margin-top: auto; margin-bottom: auto; } flex-container>flex-spacer, flex-container>flex-footer { border: 4px solid chartreuse; } flex-container>flex-item>flex-item { border: 4px solid aqua; height: 50px; width: 50px; margin: 0 5px; } 
 <flex-container> <flex-spacer></flex-spacer> <flex-item> <flex-item></flex-item> <flex-item></flex-item> <flex-item></flex-item> </flex-item> <flex-footer> this is the footer element<br /> this is the footer element<br /> </flex-footer> </flex-container> 

您需要的是一个用于整个容器的flexbox,以及一个用于内容本身的嵌套flexbox。 这使您可以应用两个不同的对齐规则,同时保持flexbox闻名的“灵活性”。

您的其他一些元素(例如“间隔符”)是不必要的。

 flex-container { display: flex; flex-direction:column; align-items: center; justify-content:flex-end; border: 4px solid blue; height: 300px; width: 300px; } flex-container > flex-center-content { display:flex; height:100%; width:100%; align-items:center; justify-content:center; } flex-container > flex-footer { border: 4px solid chartreuse; } flex-container > flex-center-content > flex-item { border: 4px solid aqua; height: 50px; width: 50px; margin: 0 5px; } 
 <flex-container> <flex-center-content> <flex-item></flex-item> <flex-item></flex-item> <flex-item></flex-item> </flex-center-content> <flex-footer> this is the footer element<br /> this is the footer element<br /> this is footeeeeer<br> look how tall I am<br> and how much I push things<br> </flex-footer> </flex-container> 

小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM