【问题标题】:Is there a way to create a mask using CSS (example image in body)有没有办法使用 CSS 创建蒙版(正文中的示例图像)
【发布时间】:2019-02-19 16:47:09
【问题描述】:

Example image demonstrating what I need

如果您看到上面的图像,则有一个父容器应用了一个渐变的背景图像。它分为垂直堆叠的 2 个细分。其中一个 div 包含一个绝对定位的红色 div 和一个蓝色 div。蓝色 div 应该像一个只覆盖 subdiv2 内容的掩码。它锚定到 subdiv2 中的其他东西(不在图像中),因此如果“某物”移动,它就会移动。如果它恰好覆盖了红色div,它应该在保留渐变背景的同时隐藏红色div。有没有办法使用css来实现这一点?

如果渐变不存在,One 将沿链继承背景颜色,而蓝色 div 将简单地隐藏红色 div。如果您继承背景图像,我们会在 2 个细分中得到一个不正确的分割渐变。如果我们保持 2 个细分的背景透明,我不知道蓝色 div 没有办法隐藏红色 div。

谢谢!

EDIT :抱歉之前没有指定。我的错。我已经更改了措辞,以确保你们理解蓝色 div 并不总是覆盖红色 div 的事实,否则解决方案会很简单。

【问题讨论】:

    标签: css sass


    【解决方案1】:

    You can check this example out. 你可以使用

    background: inherit

    将红色 div 的 z-index 设置为 -1 后在蓝色 div 上。

    在蓝色 div 上使用背景继承将有助于它不会失去透明度,并且会消失红色 div。 在红色 div 上使用 z-index:-1 会将其推到蓝色 div 后面。

    【讨论】:

    • 感谢您的回答!这适用于同质背景。由于我有渐变背景,当 2 个细分(和蓝色 div)继承它时,渐变会分裂并且看起来完全不均匀。所以这个解决方案对我不起作用。
    【解决方案2】:

    如果父 div 有background:transparent,它会给你想要的效果。困难的部分是让父母“站在”孩子面前。我可以通过在孩子身上设置一个否定的z-index 来做到这一点,但你可能需要别的东西。如果没有看到您的标记,我无法确定。

    document.getElementById('toggle').onclick = () => {
      const inner = document.getElementById('inner');
      const style = window.getComputedStyle(inner);
      const index = style.getPropertyValue('z-index');
      document.getElementById('inner').style.zIndex = index === "-1" ? "0" : "-1";
    }
    .bg {
      width:600px;
      height:400px;
      background:url(http://placekitten.com/600/400);
    }
    
    .div1 {
      height:200px;
      border: 2px solid red;
    }
    
    .div2 {
      position:relative;
    }
    
    .subdiv2 {
      position:absolute;
      left:40%;
      top:80px;
      height:80px;
      width:200px;
      border: 2px solid blue;
      background:transparent;
    }
    
    #inner {
      position:absolute;
      top:10px;
      left:80px;
      width:60px;
      height:60px;
      background:red;
      z-index:-1;
    }
    <div class="bg">
      <div class="div1"></div>
      <div class="div2">
        <div class="subdiv2">
          <div id="inner"></div>
        </div>
      </div>
    </div>
    <button id="toggle">toggle z-index</button>

    【讨论】:

      【解决方案3】:

      z-index 似乎是解决这个问题的坏方法。您可以为 z-index 值设置动画,但随着元素改变深度并在彼此之间传递,它仍然看起来有点有趣。

      如果目标是用其父背景在视觉上“隐藏”内容,透明度不是相同的结果吗?还是我错过了目标?

      我建议:

      // hidden state
      .redDiv {
       opacity:0;
       transition: opacity 0.5s linear;
      }
      
      // visible state
      .redDiv.visibleState {
       opacity:1;
      }
      

      您可以使用real masking in CSS,但我倾向于为复杂的形状保留它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-20
        • 2011-03-22
        • 2019-07-09
        • 2022-11-23
        • 1970-01-01
        • 2022-08-22
        • 2019-05-17
        相关资源
        最近更新 更多