【问题标题】:color image inside grayscale(100%) container灰度(100%)容器内的彩色图像
【发布时间】:2016-07-02 21:33:06
【问题描述】:

我有一个带有背景图像的 div,我正在使用过滤器将其显示为黑白 (filter: grayscale(100%);)。我现在正试图在该 div 中放置一个颜色图标。尝试将图标设置为grayscale(0%),但这似乎不起作用。

这是一个例子:

#a1, #a2 {
  background-image: url(http://ndrichardson.com/blog/wp-content/uploads/2012/04/colorpsychology.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
#a1 {
  height: 250px;
  width: 250px;
  -webkit-filter: grayscale(100%);
  filter: grayscale(100%);
  position: relative;
}
#a2 {
  height: 50px;
  width: 50px;
  -webkit-filter: grayscale(0%);
  filter: grayscale(0%);
  position: absolute;
  top: 0px;
  right: 0px;
}
<div id="a1"><!-- << this should be black and white -->
  <div id="a2"><!-- << this should be color -->
  </div>
</div>

有没有办法在不创建额外的 div 来保存背景图像的情况下做到这一点?真正的代码要复杂得多,这就是为什么我想尽可能避免使用额外的 div。

【问题讨论】:

    标签: html css css-filters


    【解决方案1】:

    是的,当然,你应该使用::before::after 伪元素:

    #a1 {
      height: 250px;
      width: 250px;
      position: relative;
    }
    #a1:after, #a1:before {
      content: '';
      background-image: url(http://ndrichardson.com/blog/wp-content/uploads/2012/04/colorpsychology.jpg);
      background-repeat: no-repeat;
      background-size: 100% 100%;  
      position: absolute;
    }
    #a1:before {
      -webkit-filter: grayscale(100%);
      filter: grayscale(100%);
      width: 100%;
      height: 100%;
    }
    #a1:after {
      height: 50px;
      width: 50px;
      top: 0px;
      right: 0px;
    }
    &lt;div id="a1"&gt;&lt;/div&gt;

    DEMO on JSFiddle

    【讨论】:

      【解决方案2】:

      filter: grayscale(100%) 的容器内不可能有颜色。

      请参阅规范中的the filter property(强调我的):

      none 以外的计算值会导致创建 stacking context 与 CSS opacity 的方式相同。全部 元素后代被呈现为一个组与 应用于整个组的过滤效果

      所以是的,您必须将带有过滤器的内容与没有过滤器的内容分开。

      这并不一定意味着您需要在 HTML 中添加额外的包装器,因为 Hiszpan 建议您也可以使用伪元素。

      【讨论】:

        猜你喜欢
        • 2021-10-06
        • 2015-11-20
        • 2013-07-28
        • 1970-01-01
        • 2011-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多