如何使用HTML与CSS在图片下方添加文字(已引入Bootstrap框架)
实现方案
你项目已经引入Bootstrap 5,直接用框架自带的figure组件即可快速实现图片+下方说明的布局,不需要额外引入其他依赖,调整步骤如下:
- 调整HTML结构:将每一张图片和对应说明文字封装到独立的
figure容器中,用Bootstrap自带的d-inline-block类让三个图文组保持横向排列,figure-caption标签专门用于承载图片下方的说明文字 - 微调CSS样式:将原本加在图片上的右外边距转移到
figure容器上,保证横向布局间距和你原有设置完全一致
以下是修改后的完整可运行代码:
样式部分
body { overflow-x: hidden; } .design { width: 771px; height: 568px; margin-left: 364px; margin-right: 365px; margin-top: 247px; margin-bottom: 200px; } /* 保留原有横向间距设置 */ .figure-group1 { margin-right: 116px; } .figure-group2 { margin-right: 81px; } .figure-group3 { margin-right: 60px; } .image1 { width: 138px; height: 92px; margin-top: 33px; margin-left: 24px; } .image2 { width: 99px; height: 98px; margin-top: 35px; margin-left: 24px; } .image3 { width: 79px; height: 90px; margin-top: 39px; margin-left: 25.7px; } /* 说明文字样式,可按需修改字号、颜色、边距 */ .figure-caption { font-size: 14px; color: #212529; margin-top: 8px; text-align: center; }
HTML部分
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Horseradish</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-uWxY/CJNBR+1zjPWmfnSnVxwRheevXITnMqoEIeG1LJrdI0GlVs/9cVSyPYXdcSF" crossorigin="anonymous" /> <style> /* 把上面的样式代码放到这里即可 */ </style> </head> <body> <header> <div class="row"> <div class="col-6"></div> <div class="col"> <div class="text-end"> <!-- 第一张图+说明 --> <figure class="figure d-inline-block figure-group1"> <img src="images/location.png" alt="" class="image1 d-block" /> <figcaption class="figure-caption">第一张图的说明文字</figcaption> </figure> <!-- 第二张图+说明 --> <figure class="figure d-inline-block figure-group2"> <img src="images/how.png" alt="" class="image2 d-block" /> <figcaption class="figure-caption">第二张图的说明文字</figcaption> </figure> <!-- 第三张图+说明 --> <figure class="figure d-inline-block figure-group3"> <img src="images/why.png" alt="" class="image3 d-block" /> <figcaption class="figure-caption">第三张图的说明文字</figcaption> </figure> </div> </div> </div> </header> <img src="images/home.png" alt="" class="design" /> </body> </html>
如果需要调整说明文字和图片的对齐方式、间距,直接修改.figure-caption的样式属性即可。
内容的提问来源于stack exchange,提问作者user16052862
相关产品推荐
相关产品推荐

