Background opacity with one line of CSS
When you want to display text on a background image, you need some contrast to make the text readable. The most common and easiest way to achieve this contrast is to add a dark transparent overlay on the image. Something like this:
There are a few different ways to do that, but unfortunately, none of them are straight forward. There is no property like "background-opacity" that can help you get this.
I always used to add another <div>
within the section with a transparent dark background-color
like rgba(0, 0, 0, 0.5)
, give it a position: absolute
and inset: 0
to get this result.
Ugh, messy!
Thankfully you don't have to do that.
Multiple Backgrounds and Linear Gradients
The background-image
property can take multiple values separated by commas:
background-image: <image1>, <image2>, ...
To achieve our desired layout, what we need is:
<image1>
to be a dark transparent background image and
<image2>
to be our photo
But we cannot do something like:
background-image:
rgba(0, 0, 0. 0.5)
, <image2>
because background-image cannot take color as a value.
However, we can do this:
background-image:
linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5))
, <image2>
Linear gradients can be used a background images. Here, we are using a transparent gray color as the starting and ending colors for this linear gradient.
And that's it! We have our transparent background overlay with this single line of CSS. You don't even need to add any additional elements in HTML.
Hope you enjoyed reading this :)
📘 Complete Guide to CSS Flex and Grid
If you loved this write-up and how it was explained, you’ll absolutely love my eBook CSS Flex and Grid. Check it out!
📨 Newsletter suggestion
I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇
Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.