Explain Codes LogoExplain Codes Logo

Darken CSS background image?

html
responsive-design
css-variables
browser-compatibility
Anton ShumikhinbyAnton Shumikhin·Nov 24, 2024
TLDR

Instantly darken a CSS background image using a translucent black ::after pseudo-element:

.your-element::after { content: ''; position: absolute; top: 0; background: rgba(0, 0, 0, 0.6); /* Darkened version. Make it 90% darker too... */ width: 100%; height: 100%; }

Updating the rgba alpha value allows for increasing or decreasing the darkening effect—just like sun shades for your images! Remember to set your parent element to position: relative.

Dive into details

A new way: gradient overlays

Want the power of precision? CSS3 linear gradients are your hero. Create a gradient with same starting/ending colors and overlap your background image:

.your-element { background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('your-image.png'); }

Like the alpha commandos, adjust the values to achieve your darkening mission.

Safety nets: fallbacks and transparency

When rgba and gradients pair up, you have the power to adjust image transparency — it's like having an invisible cape! If your image fails to load, having a fallback color is your insurance:

.your-element { background-color: gray; /* Plan B in action */ /* ...other styles... */ }

Tailor your image: Positioning and size

Use the background-position and background-size to tailor your image and overlay on different screens. Ensure your UI elements aren't playing hide-and-seek under the overlay!

Dare to be different

Image manipulation: CSS filters

Darkening your image is like adding the right spices to a dish. You can experiment with the brightness() filter on .your-element:

.your-element { filter: brightness(60%); }

This charming devil offers great power but needs extensive cross-browser testing. So, strap your safety belts!

Being inclusive: Browser compatibility

Not all browsers are created equal. For those less privileged, opt for polyfills or simpler background colors.

Step up your game

Test various opacity values and mix-blend-modes for the perfect shade! Just think of it as, "Fifty Shades of CSS" 😂

The cherry on top: CSS variables

For real-time darkness level adjustments, leverage the power of CSS variables. Use JavaScript to tweak these variables and watch your styles change live!