How to darken a background using CSS?
For an immediate solution, overlay a transparent black layer on your element's background using rgba(0, 0, 0, 0.5)
. Here's the necessary CSS:
The element with .darken
should be set as position: relative;
to contain the overlay. The opacity within rgba
controls the darkness.
Technically dark modes
If rgba
alone doesn't cut it for you, you can spice things up by using linear-gradient
, background-blend-mode
, filter
, or pseudo-elements.
Darkening with linear-gradient
A layered background with linear-gradient allows us to easily darken background images.
Blend and filter effects
The background-blend-mode
property offers ways of blending your background-color and image for different effects. filter: brightness(50%)
leans into the image's brightness and turns it down a notch. These techniques are like your computer-based photo editing software.
Ensure you cross-verify the cross-browser compatibility for these properties on caniuse.com.
Pseudo-elements as dark overlords
A ::after
can provide a dark overlay elegantly. With absolute positioning, this feature stretches to cover the whole element like a wormhole covers...worms? It's fluid as butter thanks to transitions.
box-shadow
armed with inset
and RGBA
. Sounds like a Marvel superhero, right? It's actually an inner shadow that darkens the element from the edges.
Exploring Uncharted Darkness
If these methods are too vanilla for you, let's go extreme. Add transparent gradients, inset shadows, and hover effects to your arsenal.
Transparent gradient darkening.
The linear-gradient
property amplifies the visual depth of your shadow. Look ma, weβre making art!
Darken from the edges
By setting box-shadow
with inset
, poof! You create a vignette effect. It darkens the edges and simultaneously brightens the center.
Hover-Darkening
For a dramatic entrance, use transition properties and darken your element on hover.
The interactive luminescent dance of the background deepens the connection between user and interface.
Was this article helpful?