Is there a CSS and/or JS hack to effect the darkness of a background image directly?

To set the darkness of a background image we can:

  • Make the image darker in a image manipulation tool.
  • Put the text in a <div> on top of a <div> containing the image as a background image and make the first <div> to have a transparent background this way background: rgba(0,0,0,0.50);

But is there a CSS and/or JS hack to effect the darkness of a background image directly?

By the way, I don’t mind trying something experimental in this case.

:slight_smile:

Depending on how much browser support you need, just apply a filter

img.darken {
  filter: brightness(50%);
}

6 Likes

My problem is that if the image is a background image, then this approach also effects the font color.

.homepage_after_hero {
	background: url("IMAGE");
	background-size: cover;
	background-position: top;
	background-repeat: no-repeat;
	filter: brightness(50%);
}

.homepage_after_hero_text {
	padding:50px;
	/* background:rgba(0,0,0,0.70); */
}

OK, first order of business. You do realize that an image and a background-image are not the same, correct? One is in and affects the document flow, and the other is purely decorative.

I just say that because details matter, and the approach needed to solve the same “end result” are totally different. To darken a background image, you overlay a gradient over top of it.

.bg {
  background-image: linear-gradient(rgba(0, 0, 0, 0.527),rgba(0, 0, 0, 0.5)) , url(IMG_URL);
  background-size: contain;
}

I’ve updated the code pen above with a div that uses a background image.

3 Likes

That seems to me to work just fine after double checking it (“URL” path omitted) and whitespaces added.in the `linear-gradient part.

.homepage_after_hero {
	padding:50px;
	background-image: linear-gradient( rgba(0, 0, 0, 0.70), rgba(0, 0, 0, 0.70) ), url("IMAGE");
	background-size: cover;
	background-position: top;
	background-repeat: no-repeat;
}

.homepage_after_hero h2, .homepage_after_hero h3, .homepage_after_hero p {
	margin-block: unset !important;
	margin-bottom: 25px !important;
	color: #fff;
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.