How to darken the background (images) in CSS

Владимир Самойлов
Дата: 17.08.2022
Comments: 0
Views: 29504
Content:

Let’s say right away that there are various ways to solve such a problem as darkening the background of a picture. There is no single correct method. You do it in the way that suits you best and suits your particular case.

Let’s start with the HTML for clarity:

<div class="item">
  <div class="item-photo">
    <img src="https://images.unsplash.com/photo-1616530020606-e15459064769?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=967&q=80" alt="">
  </div>
</div>

Here we have inserted our picture inside the item-photo class block.

And then let’s move on to CSS

.item-photo {
  position: relative;
}

.item-photo img {
  width: 100%;
}

.item-photo:after {
  content: '';
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0; left: 0;
  background-color: rgba(0,0,0,0.5);
}

What are we doing here? We add a transparent background over the item-photo class block with the :after pseudo element.

Note this line:

background-color: rgba(0,0,0,0.5);

Here we set the background of our pseudo-element. If we were using 1 instead of 0.5, the picture would be completely covered by a black background. You can experiment and choose any other number between 0 and 1.

You can also set a gradient instead of a simple fill. That is to fade darkening to the bottom of the picture for example. This is how to do it:

.item-photo {
  position: relative;
}

.item-photo img {
  width: 100%;
}

.item-photo:after {
  content: '';
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0; left: 0;
  background: linear-gradient(to bottom, transparent 0%,  rgba(0,0,0,0.9) 100%);
}
Darkening the picture

This is one method of how to make a darkening for a picture. You can suggest your own variant in the comments – I’m sure it will be very useful for beginners.

Was the article helpful?
👍
Yes - 28
👎
Not - 40
Comments: