HTML模糊背景图叠加文字显示异常,该如何修复
问题根因
- 所有设置了
position: absolute的文字块,默认是相对于整个页面根元素定位的,你两个文字块都设置了top: 50%; left: 50%,坐标完全相同,所以第二个文字块和第一个重叠了,自然不会显示在第二张图片的上方。 - 每个模糊背景和对应文字没有包裹在独立的相对定位容器内,绝对定位找不到正确的参照基准。
修复方案
给每组「模糊背景+文字」套一个独立的父容器,给父容器设置position: relative,让内部的文字块相对于当前父容器定位即可,同时可以优化重复的CSS代码减少冗余。
修复后完整代码如下:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body, html { min-height: 100%; margin: 0; font-family: Arial, Helvetica, sans-serif; } * { box-sizing: border-box; } /* 每组图片+文字的公共父容器 */ .car-card { position: relative; height: 100vh; overflow: hidden; } /* 模糊背景公共样式 */ .bg-image { filter: blur(8px); -webkit-filter: blur(8px); height: 100%; background-position: center; background-repeat: no-repeat; background-size: cover; } /* 单独设置不同背景图 */ .car-1 { background-image: url("https://th.bing.com/th/id/R.4418ff70835bb7e45f3b5d83c7ff5f5e?rik=bD4DENSEINH8%2bA&riu=http%3a%2f%2fwallup.net%2fwp-content%2fuploads%2f2017%2f03%2f28%2f439234-sports_car-vehicle-Lamborghini-Italian_Supercars.jpg&ehk=kG5ZwFnums33xnh3qxViA8B4WZ73wbUAjrictsOSXbU%3d&risl=&pid=ImgRaw&r=0"); } .car-2 { background-image: url("https://th.bing.com/th/id/OIP.WZziNQ9wRCIosw1FGPkJsAHaEK?pid=ImgDet&rs=1"); } /* 文字公共样式,相对于父容器car-card定位 */ .bg-text { background-color: rgb(0,0,0); background-color: rgba(0,0,0, 0.4); color: white; font-weight: bold; border: 3px solid #f1f1f1; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 80%; padding: 20px; text-align: center; } </style> </head> <body> <!-- 第一组图片+文字 --> <div class="car-card"> <div class="bg-image car-1"></div> <div class="bg-text"> <h2>模糊背景</h2> <h1>我的汽车网站</h1> <p>这是模糊处理的兰博基尼</p> </div> </div> <!-- 第二组图片+文字 --> <div class="car-card"> <div class="bg-image car-2"></div> <div class="bg-text"> <h2>模糊背景</h2> <h1>我的汽车网站</h1> <p>这是模糊处理的兰博基尼</p> </div> </div> </body> </html>
优化说明
- 抽取了重复的CSS样式,不需要为每张图、每个文字单独写一套样式,后续加更多车型卡片只需要新增对应背景图类即可,维护更方便。
- 父容器设置
position: relative后,内部文字的绝对定位只会在当前卡片范围内生效,不会出现位置偏移重叠的问题。
内容的提问来源于stack exchange,提问作者alex
相关产品推荐
相关产品推荐

