24/04/2026
Mastering CSS: How to Set Background Opacity Properly
Using the opacity property on a parent container is a common pitfall. It forces all child elements—text, buttons, and icons—to inherit the transparency, often violating WCAG accessibility standards due to poor contrast.
For a professional UI, the goal is Layer Isolation: keeping the background dim while the content remains 100% crisp.
The Industry Standard: Pseudo-Elements
Instead of affecting the whole node tree, we inject a dedicated background layer using ::before. This decouples the visual weight of the image from the legibility of the text.
Implementation:
css
/* 1. Establish a positioning context */hero-section {
position: relative;
background-color: #000; /* Serves as a tint base */
overflow: hidden;
}
/* 2. Create an isolated background layer */hero-section::before {
content: "";
position: absolute;
inset: 0; /* Modern shorthand for top/left/right/bottom: 0 */
background: url('hero-bg.jpg') center/cover no-repeat;
opacity: 0.4; /* Controlled independently */
z-index: 1;
}
/* 3. Lift content above the background */hero-content {
position: relative;
z-index: 2;
color: ;
}
Используйте код с осторожностью.
Why this approach wins:
Accessibility: Maintains maximum contrast for typography, ensuring readability across all devices.
Performance: Transitions or animations on isolated layers can be GPU-accelerated, resulting in smoother 60fps effects.
Clean Markup: Achieves complex layering without polluting the HTML with "wrapper" divs.
Flexibility: Allows for easy addition of backdrop-filter or complex gradients on the same layer.
Design Tip: When using light text, always set a dark background-color on the parent. This ensures the text remains readable even if the image fails to load.