CSS遮罩层(mask)异常:背景图遮罩同时影响标题与按钮问题咨询
解决遮罩层覆盖内容的问题
问题出在遮罩层未正确定位,导致它与文本内容处于同一层级并覆盖了内容。以下是修复方案:
- 给header容器添加
position: relative,作为遮罩层的定位参考 - 给mask元素设置绝对定位,让它铺满整个header区域,且仅覆盖背景图片
修改后的完整代码:
<!-- Header - set the background image for the header in the line below--> <header class="bg-image d-flex justify-content-center align-items-center" style="background-image: url('img/orange.jpg'); background-size: cover; height: 75vh; position: relative;"> <div class="mask" style="background-color: rgba(0, 0, 0, 0.6); position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></div> <div class="text-center my-5"> <h1 class="text-white p-5">100% blended fruit juice concentrate<span style = "display: block;">specifically designed for childcare centers</span> </h1> <a href="./ordernow.html" class="btn btn-primary btn-lg active" role="button" aria-pressed="true">Order Now</a> </div> </header>
原理说明
position: relative使header成为绝对定位子元素的参考容器- 遮罩层的绝对定位会让它脱离文档流,完全覆盖header的背景区域,但不会干扰正常文档流中的文本内容
- 文本容器作为flex布局的子元素,默认层级高于绝对定位的遮罩层,因此不会被遮罩变暗
内容的提问来源于stack exchange,提问作者John Johnson
相关产品推荐
相关产品推荐

