How to make a transparent background
Short answer
Add transparency to the background color after a slash:
<div style="padding: 16px; background: url(/media/photo-400x250.jpg) center / cover;">
<p style="margin: 0; padding: 12px; background: rgb(255 255 255 / 70%);">White background at 70%, text fully solid</p>
</div>The last number is the opacity: 0% is fully transparent, 100% is solid. You can also write a fraction: 0.7.
Other formats
Every color format has an alpha channel:
.a { background: hsl(200 80% 50% / 0.3); }
.b { background: #00808080; } /* the last two hex digits are alpha */
.c { background: transparent; }Why not opacity
opacity makes the whole element transparent, including the text and children. Compare:
<div style="padding: 12px; background: url(/media/photo-400x250.jpg) center / cover;">
<p style="padding: 8px; background: black; color: white; opacity: 0.5;">opacity: text fades too</p>
<p style="margin: 0; padding: 8px; background: rgb(0 0 0 / 50%); color: white;">rgb alpha: text stays solid</p>
</div>Common mistake
People try to make the text solid again with opacity: 1 on a child — it will not work: the parent's opacity applies to everything inside, and a child cannot be "more opaque" than it. Make only the background color transparent.
Functions used in this recipe
- rgb() — A color from red, green and blue components, with optional transparency.
- opacity — The transparency of the whole element together with its content.
- background-color — The background color of an element.