如何使用Bootstrap 5实现遮罩完整覆盖整张图片
Bootstrap 5 图片遮罩全覆盖实现方案
仅需基于现有代码添加Bootstrap内置的定位工具类即可实现需求,无需额外编写自定义CSS:
- 外层容器
.bg-image添加position-relative类,设定为相对定位,作为遮罩层的定位参照 - 遮罩层
.mask添加position-absolute、top-0、start-0、w-100、h-100类,让遮罩完全铺满父容器尺寸,刚好覆盖下方图片
修改后的完整代码如下:
<!-- Bootstrap-5 --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <!-- 主体代码 --> <div class="bg-image position-relative"> <img src="https://mdbootstrap.com/img/new/standard/city/053.jpg" class="w-100" /> <div class="mask position-absolute top-0 start-0 w-100 h-100" style="background-color: rgba(0, 0, 0, 0.6)"></div> </div>
如果需要在遮罩上叠加展示文字,可直接将文字内容放入.mask容器内,还可搭配Bootstrap的弹性布局工具类实现文字居中,示例如下:
<div class="mask position-absolute top-0 start-0 w-100 h-100 d-flex align-items-center justify-content-center text-white" style="background-color: rgba(0, 0, 0, 0.6)"> <h1>遮罩上的展示文字</h1> </div>
内容的提问来源于stack exchange,提问作者ShrockCo
相关产品推荐
相关产品推荐

