如何用Flexbox实现li元素顶部对齐并超封面高度时垂直并排
布局问题解决方案:曲目列表高度超出封面时自动垂直分栏
需求说明
当动态生成的曲目(<li>元素)总高度超过专辑封面高度时,希望曲目列表能自动垂直并排(分栏)显示。
原HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./style.css"> <title>What</title> </head> <body> <main> <div class="album-container"> <img src="" class="cover"> <div class="album-info"> <div class="title-info"> <h2 class="title">Title</h2> <h3 class="artist">Playboi Carti</h3> <span class="year">Year</span> </div> <ul class="tracks"> <!-- li tags gon be dynamically created by script --> </ul> </div> </div> <button class="btnChange">Look</button> </main> <script src="./app.js"></script> </body> </html>
修改后的CSS代码
@import url('https://fonts.googleapis.com/css2?family=M+PLUS+Rounded+1c&display=swap'); img{ max-width: 400px; max-height: 400px; } *{ box-sizing: border-box; margin: 0; padding: 0; text-decoration: none; list-style-type: none; font-family: 'M PLUS Rounded 1c', sans-serif; } body{ background-color: #0a0908; color: white; height: 100vh; overflow: auto; } main{ height: 100%; display: flex; align-items: center; justify-content: center; flex-direction: column; padding: 20px; } ul.tracks{ column-width: 200px; column-gap: 20px; max-height: calc(400px - 80px); overflow-y: auto; } li{ padding: 5px; break-inside: avoid; } .album-container{ margin-bottom: 20px; display: flex; justify-content: space-between; flex-wrap: wrap; align-items: flex-start; } .album-info{ margin-left: 20px; flex: 1; min-width: 200px; max-height: 400px; } .title-info{ margin-bottom: 15px; } .btnChange{ padding: 8px 16px; cursor: pointer; }
关键修改说明
- 移除全局
overflow: hidden:避免截断分栏后的曲目内容,同时给body添加overflow: auto,确保页面内容过多时可滚动。 - 统一容器高度基准:将
.album-info的最大高度设置为和专辑封面一致的400px,让曲目列表的高度参考标准与封面对齐。 - CSS多列布局实现自动分栏:通过
column-width定义每列最小宽度,当曲目总高度超出容器时自动生成垂直列;break-inside: avoid保证单个曲目不会被拆分到两列。 - 适配标题区域高度:用
calc(400px - 80px)计算曲目列表的最大高度,减去标题区域的占用空间,避免内容超出容器;添加overflow-y: auto允许列表内部滚动。 - 优化视觉对齐:给
.album-container添加align-items: flex-start,让封面与专辑信息顶部对齐,提升整体视觉协调性。
内容的提问来源于stack exchange,提问作者merkezci
相关产品推荐
相关产品推荐

