如何用纯CSS实现flex列表项自适应最高项高度并合理排布内容
纯CSS实现等高列表项并生效justify-content: space-between
问题描述
我有一个由<ul>和<li>组成的菜单,简化代码如下。我不希望给<ul>或<li>设置固定px高度,当前<li>使用height: fit-content,<li>的高度会随内部文本内容变化。我希望所有<li>都和最高的<li>(或父级flex容器<ul>)高度一致,同时让div.wrapp能生效justify-content: space-between。目前通过JavaScript获取最高<li>的高度可以实现,但是否有更简便的纯CSS解决方案?
原代码
CSS
.ul_listing { display: flex; flex-direction: row; width: 450px; } .lists { display: flex; /*height: 250px; /*works with fixed height */ height: fit-content; /*does not work with fit-content*/ } .wrapp { display: flex; align-items: center; flex-direction: column; justify-content: space-between; /* does not work if fit-content for li */ }
HTML
<ul class="ul_listing"> <li class="lists"><a href=""><div class="wrapp"><p>testint</p><img src="https://picsum.photos/id/237/200/300" width="50px" height="50px" alt=""></div></a></li> <li class="lists"><a href=""><div class="wrapp"><p>testing length</p><img src="https://picsum.photos/id/237/200/300" width="50px" height="50px" alt=""></div></a></li> <li class="lists"><a href=""><div class="wrapp"><p>testing lenth of text</p><img src="https://picsum.photos/id/237/200/300" width="50px" height="50px" alt=""></div></a></li> <li class="lists"><a href=""><div class="wrapp"><p>testing big length when text on li</p><img src="https://picsum.photos/id/237/200/300" width="50px" height="50px" alt=""></div></a></li> </ul>
纯CSS解决方案
只需要调整几个flex相关属性就能实现需求,无需JS:
- 给父容器
.ul_listing明确设置align-items: stretch(flex容器默认值,显式设置避免意外),让所有<li>自动拉伸至最高项的高度 - 给
.lists设置flex: 1(或指定宽度),移除height: fit-content,让列表项跟随父容器拉伸 - 给
.wrapp设置height: 100%和width: 100%,使其撑满<li>的高度,此时justify-content: space-between即可生效
修改后的CSS代码
.ul_listing { display: flex; flex-direction: row; width: 450px; align-items: stretch; /* 确保列表项等高 */ } .lists { display: flex; flex: 1; /* 平分容器宽度,也可设置固定宽度 */ /* 移除height: fit-content,让列表项自动拉伸 */ } .wrapp { display: flex; align-items: center; flex-direction: column; justify-content: space-between; height: 100%; /* 撑满父元素高度,激活space-between */ width: 100%; /* 确保内部元素填满列表项宽度 */ padding: 8px; /* 可选,优化内边距提升视觉效果 */ }
原理说明
align-items: stretch会让flex容器的子元素(<li>)沿交叉轴(垂直方向)拉伸至与最高子元素同高,完全适配内容高度,无需固定值.wrapp设置height: 100%后,会填充整个<li>的高度,此时flex-direction: column配合justify-content: space-between会让内部的文本和图片分别靠顶部、底部排列,中间自动留白
内容的提问来源于stack exchange,提问作者Mehdi
相关产品推荐
相关产品推荐

