HTML/CSS 如何让多张图片及下方文字保持同一行水平对齐
数据小陈
结论
别用 <br> 做布局。把 5 个“图片 + 说明文字”单元放进同一个父容器,用 CSS Grid 固定为 5 列;每个单元内部让图片 display:block; width:100%,说明文字放进单独的 figcaption 或 div。这样加了说明文字,列也不会被挤到下一行。
为什么会变成上下排列
span默认是行内元素,max-width对它一般不起作用,宽度由内容决定。- 每个单元里用
<br>换行,浏览器会强制断行,5 个单元很难稳定留在同一行。 </br>不是合法的br闭合写法。浏览器会容错,但不建议依赖。text-align: justify只影响行内内容的分布,不会创建 5 个等宽列。
推荐写法
HTML 可以这样写:每个海报用一个 figure,外层 div 作为行容器。
<div class='poster-row'>
<figure class='imgs-with-text'>
<img src='Images/gwhposter1.jpg' alt='Good Will Hunting poster'>
<figcaption>
<div>Good Will Hunting</div>
<div>Gus Van Gus, 1997</div>
</figcaption>
</figure>
<figure class='imgs-with-text'>
<img src='Images/dpsposter1.jpg' alt='Dead poets society poster'>
<figcaption>
<div>Dead Poets Society</div>
<div>Peter Wiel, 1989</div>
</figcaption>
</figure>
<figure class='imgs-with-text'>
<img src='Images/tbcposter1.jpg' alt='The Breakfast Club poster'>
<figcaption>
<div>The Breakfast Club</div>
<div><i>Gus Van Gus, 1997</i></div>
</figcaption>
</figure>
<figure class='imgs-with-text'>
<img src='Images/ddposter1.jpg' alt='Donnie Darko poster'>
<figcaption>
<div>Donnie Darko</div>
<div>Gus Van Gus, 1997</div>
</figcaption>
</figure>
<figure class='imgs-with-text'>
<img src='Images/msposter1.jpg' alt='Mysterious skin poster'>
<figcaption>
<div>Mysterious Skin</div>
<div>Gus Van Gus, 1997</div>
</figcaption>
</figure>
</div>
CSS:
.poster-row {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 1.5%;
align-items: start;
width: 100%;
}
.imgs-with-text {
margin: 0;
min-width: 0;
text-align: center;
font-size: 12px;
}
.imgs-with-text img {
display: block;
width: 100%;
height: auto;
}
.imgs-with-text figcaption {
margin-top: 0.35em;
line-height: 1.3;
}
注意事项
grid-template-columns: repeat(5, minmax(0, 1fr))保证 5 列等宽,gap控制列间距,不需要再给图片左右各加2.5%的 margin。- 如果希望所有海报图片高度一致,可以给图片加
aspect-ratio和object-fit: cover,比例按实际海报调整,例如aspect-ratio: 2 / 3; object-fit: cover;。不加则按原图比例显示,图片高度可能不同。 - 需要顶部对齐用
align-items: start;需要底边对齐可改为align-items: end。 - 原代码中的
font-size: 5px一般过小,建议按页面实际字号调整。
备注:内容仅供参考。
