How can I make a CSS background color transparent without affecting the text?

I want the background of my list menu to be transparent using CSS, but I don’t want the text or font to become transparent. Is it possible to achieve this using CSS background color transparent techniques in CSS3?

Hey! I’ve dealt with this exact issue :sweat_smile:. The trick is to make the background color transparent without affecting the text. I usually do it with rgba:

.menu {
    background-color: rgba(0, 0, 0, 0.5); /* black background at 50% opacity */
    color: white; /* text stays fully opaque */
}

The a in rgba controls the alpha (opacity).

Text color remains unaffected because rgba only applies to the background, not the content.

I use this method all the time for overlays or semi-transparent menus.

You can use the opacity property, but a word of caution:

.menu {
    opacity: 0.5; /* makes everything, including text, semi-transparent */
}

The downside is text and child elements also become transparent, which is usually not what you want.

I only use this if I want the entire element (including text) to fade.

Using pseudo-elements for background transparency

If you want a semi-transparent background while keeping the text fully opaque, another approach is using ::before:

.menu {
    position: relative;
    color: white; /* text stays opaque */
}

.menu::before {
    content: "";
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    background-color: black;
    opacity: 0.5; /* only background is transparent */
    z-index: -1;  /* behind the text */
}

This separates the background from the text completely.

I use this when I need more control over layers or for complex layouts.