Search code examples
htmlcsspageloadcss-filters

Reusing background image with filter


My project uses two JPGs as as background textures for two different splash screens. The images are identical, but with inverted colors. I want to know if there's a way I can eliminate the second image (inverted colors) and use filter to achieve the same result.

Trouble is, I'm not sure how to apply styles/structure content so I can limit the filter to just the background image. As it is, the entire element (text, borders) is impacted by the filter, which clashes with the rest of the design:

HTML

<header class="header">
    <div class="splash splash-one">Page Title</div>
    <div class="splash splash-two">
        <div>thing 1</div>
        <div>thing 2</div>
    </div>
</header>  

CSS

.splash-two {
    filter: invert(0.7);
    -webkit-filter: invert(0.7);
}

How can I limit the filter so that only the background image is affected, and only when it's used the second time? Until now, I've reset the filter value for all impacted children to 0, but this seems like a clunky workaround.

JavaScript solutions are appreciated, but jQuery and other libraries are a secondary solution at best. Chrome/Firefox are the only browsers I'm concerned about.


Solution

  • you can use a pseudo-element, either ::before or ::after for this.

    body {
      margin: 0
    }
    [class*="splash"] {
      height: 50px;
      width: 100%
    }
    .splash-one {
      background: url("http://lorempixel.com/1600/900") no-repeat
    }
    .splash-two::before {
      filter: invert(.7);
      -webkit-filter: invert(.7);
      content: "";
      position: absolute;
      width: 100%;
      height: 50px;
      top: 50px;
      left: 0;
      background: url("http://lorempixel.com/1600/900") no-repeat;
      z-index:-1
    }
    <header class="header">
      <div class="splash splash-one">Page Title</div>
      <div class="splash splash-two">
        <div>thing 1</div>
        <div>thing 2</div>
      </div>
    </header>