Victor A.
Victor A.

Reputation: 3

How do I add a filter to a background image in the body

I am trying to add a filter to the background image of the body. I currently am using this code:

body {
    background: url("/img/congruent_pentagon.png");
    color: white;
    font-family: "Raleway";
    -webkit-filter: grayscale(1);
}

It is making all of the child elements in grayscale but not the background image itself. I have looked into what others have done and it's mainly people manipulating html elements. That is not what I'm trying to achieve. Is it even possible to add a filter in this way? If so, how?

Upvotes: 0

Views: 399

Answers (1)

I haz kode
I haz kode

Reputation: 1625

This is just too much work compared to using Photoshop or something similar to desaturate the image.

With that being said.... You can use pseudo-element selectors for that. in my case I added the background to the pseudo-element :before

I then made sure it's sized correctly and added a negative z-index so that it always renders behind the content of the body and not on top.

Then I applied the filter to it.

I believe this is what you wanted.

body {
margin: 0 auto;
}

body:before {
  background: url("https://unsplash.it/1920/?image=1062") no-repeat center;
  background-size: 100%;
  content: "";
  height: 100vh;
  width: 100vw;
  position: fixed;
  filter: grayscale(1);
  z-index: -1;

}

.content {
  opacity: .6;
  height: 200px;
  width: 200px;
  display: inline-block;
  margin: 1em;
}

/* color fluff */
.aa {background: yellow;}
.bb {background: red;}
.cc {background: green;}
.dd {background: orange;}
<div class="container">
  <div class="content aa"></div>
  <div class="content bb"></div>
  <div class="content cc"></div>
  <div class="content dd"></div>
</div>

Upvotes: 1

Related Questions