Explain Codes LogoExplain Codes Logo

How do I reduce the opacity of an element's background using CSS?

html
css
opacity
rgba
Nikita BarsukovbyNikita Barsukov·Aug 3, 2024
TLDR

To target just the background for transparency while keeping the content opaque, you simply utilize the background-color property with rgba color values like so:

.element { background-color: rgba(255, 0, 0, 0.5); // The opacity of this red sauce is only 50% spicy }

Making sense of rgba() and optimizing fallbacks

Decoding rgba()

rgba() stands for "red, green, blue, alpha", with alpha specifically denoting opacity. By tweaking the alpha value, we adjust the background's level of transparency.

.element { background-color: rgba(0, 255, 125, 0.6); // Green, but make it 60% transparent }

Fallbacks for older bros (browsers)

For the older generation of browsers that don't speak rgba, use a solid color fallback:

.element { background: rgb(255, 0, 0); // Full strength spicy red for older taste buds (browsers) background-color: rgba(255, 0, 0, 0.5); // For those who like it mild }

Additional methods for achieving transparent backgrounds

Fashion with fashion (PNG or SVG)

rgba() may be the go-to for colour transparency, but who said PNG or SVG images can't strut the runway too? They work perfectly in giving your website a unique texture.

.element { background-image: url('see-through-dress.png'); // Because who doesn’t love patterns? }

Spotlights using pseudo-elements

Applying the clock-and-dagger technique of pseudo-elements is perfect for creating an overlay whilst keeping your content totally opaque:

.element { position: relative; // Anchors the pseudo-element to the parent } .element::before { content: ""; position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-color: rgba(255, 0, 0, 0.5); // Red spy in the base? z-index: -1; // Hide behind the bushes }

Cascade away, my CSS warriors!

Keeping content on the clear side

To keep your content crystal clear against your semi-transparent background, you want to handle .pane padding and .cont margins right:

.pane { padding: 20px; // Comfy space background-color: rgba(0, 0, 0, 0.5); // I like my background like my coffee: Black but mild }

Integrity of layout: When inline meets block

To keep a smooth layout flow going with inline elements, use display:inline-block.

.element { display:inline-block; // Keep that line! }

And speaking of blocks, don't forget to "block" absolute background elements to full dimensions with:

.background { position:absolute; width: 100%; height:100%; }

IE: The browser that lived in the past

In Internet Explorer, alpha transparency is rendered uniquely as an additional pair of digits before the hex color code: #99 stands for 60% opacity.

.element { filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, EndColorstr=#99000000); }

And a pro-tip:

<meta http-equiv="X-UA-Compatible" content="IE=edge">