如何防止图片Overlay(覆盖层)超出图片宽度?
解决Overlay超出图片宽度的问题
问题根源
你给img设置的百分比宽度是相对于父容器(section)的,而figure作为inline-block元素,默认宽度未被img约束,导致figcaption的100%宽度基于figure而非图片实际宽度。另外,figcaption用了display: inline-block和justify-content: center,这两个属性搭配错误——justify-content仅在flex容器中生效。
修复步骤
- 让figure宽度匹配图片:给figure添加
width: fit-content或直接设置对应百分比,让figure自动贴合图片宽度。 - 修正figcaption布局:将figcaption的
display改为flex,确保justify-content: center生效实现文字居中。 - 调整图片宽度控制逻辑:把img的宽度设为100%,让图片占满父容器,将宽度控制移到figure上,更易维护。
修正后的代码
CSS 代码
img.rounded { border-radius: 5%; /* 用50%可设置为圆形 */ width: 100%; /* 图片占满父容器,宽度由figure控制 */ } figure { position: relative; display: inline-block; overflow: hidden; margin: 0; /* 清除figure默认外边距 */ } /* 主热门文章的宽度 */ #trending figure { width: 50%; } /* 另外两篇热门文章的宽度 */ #twoTrending figure { width: 80%; } figcaption { position: absolute; bottom: 0; left: 0; width: 100%; padding: 5px; background-color: rgba(0, 0, 0, 0.7); color: #fff; opacity: 0; transition: opacity 0.3s ease-in-out; box-sizing: border-box; display: flex; /* 改为flex容器 */ justify-content: center; /* 水平居中文字 */ } figure:hover figcaption { opacity: 1; }
HTML 代码
<section id="trending"> <h1>Trending News</h1> <!--Main trending article--> <figure> <a href="article.html"> <img src="./images/ja.jpg" alt="Trulli" class="rounded"> <figcaption>Ja Suspended Again</figcaption> </a> </figure> </section> <section id="twoTrending"> <figure> <a href="basketball.html"> <img src="./images/bron.jpg" alt="Trulli" class="rounded"> <figcaption>Lebron announces retirement.</figcaption> </a> </figure> <!--Second trending article--> <figure> <a href="basketball.html"> <img src="./images/bron.jpg" alt="Landscape" class="rounded"> <figcaption>Another Lebron article.</figcaption> </a> </figure> </section>
额外优化(可选)
如果想让#twoTrending里的两个figure并排显示,可给该section添加flex布局:
#twoTrending { display: flex; gap: 15px; /* 控制两个figure的间距 */ }
内容的提问来源于stack exchange,提问作者Grass
相关产品推荐
相关产品推荐

