【问题标题】:How do I apply a mask over my whole image?如何在整个图像上应用蒙版?
【发布时间】:2021-09-18 01:10:23
【问题描述】:

仅使用 Bootstrap-5,我很难让面具覆盖我的整个图像。我该怎么做?

这是我的jsfiddle 和下面的代码:

<!-- 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">


<!-- Body -->
<div class="bg-image">
  <img src="https://mdbootstrap.com/img/new/standard/city/053.jpg" class="w-100" />
  <div class="mask" style="background-color: rgba(0, 0, 0, 0.6)"></div>
</div>

【问题讨论】:

    标签: html css bootstrap-5


    【解决方案1】:

    您可以在您的标记中转储一堆Bootstrap positioning classes,但由于无论如何您都需要自定义CSS,我会这样做,无论是在嵌入式标签或外部样式表中。应严格避免内联样式。它们不容易阅读或维护。

    通常的方法是使用伪元素。这可以防止需要额外的标记。请注意,我在容器上使用 Bootstrap 的 position-relative 类,而不是添加自定义样式规则。

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
    
    <style>     
      .bg-image:after {
        content: '';
        position: absolute;
        left: 0;
        width: 100%;
        top: 0;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.6);
      }
    </style>
    
    <div class="bg-image position-relative">
      <img src="https://mdbootstrap.com/img/new/standard/city/053.jpg" class="w-100" />
    </div>

    【讨论】:

      【解决方案2】:

      只需将position-relative 类添加到父元素即可。
      然后position-absolute+ top-0 + end-0 + bottom-0 + start-0 覆盖。

      默认情况下不需要 z-index。

      <!-- 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">
      
      
      <!-- Body -->
      <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 end-0 bottom-0 start-0 " style="background-color: rgba(0, 0, 0, 0.6)"></div>
      </div>

      【讨论】:

      • 应尽可能避免使用内联样式。即使是嵌入的样式标签也更好。
      • 我没有添加inline-style 我只是添加了提到的引导类。但如果他想完全使用 Bootstrap,SASS 也可以添加它。就我个人而言,我更倾向于使用自定义 CSS 来使用 inset: 0,这样代码会更短。
      • 很公平,但是将.mask 的样式移动到样式标签会很简单。
      【解决方案3】:

      要获得覆盖,您必须添加以下 css 代码:

      .bg-image{
         position: relative;
      }
      
      .mask{
         position: absolute;
         width: 100%;
         height: 100%;
         left: 0px;
         top: 0px;
      }
      

      .bg-image 提供相对位置很重要,因为您希望子元素.mask 的行为相对于它。没有它会覆盖整个body

      【讨论】:

        猜你喜欢
        • 2015-05-16
        • 1970-01-01
        • 2011-11-20
        • 1970-01-01
        • 2019-11-29
        • 1970-01-01
        • 1970-01-01
        • 2011-11-11
        • 1970-01-01
        相关资源
        最近更新 更多