Controlling Element Transparency with CSS opacity

Hero image for Controlling Element Transparency with CSS opacity. Image by David Werbrouck.
Hero image for 'Controlling Element Transparency with CSS opacity.' Image by David Werbrouck.

In CSS, the opacity property allows us to control the transparency of an element. By adjusting the opacity value, we can make elements partially or fully transparent without changing their visibility or their position within the document flow.

It is not dissimilar to CSS visibility, which I've also written about recently (although, in that case, it's more like an on/off switch, hiding and showing elements entirely).


What Is opacity?

The opacity property defines the transparency level of an element, ranging from 0 (completely transparent) to 1 (completely opaque). Intermediate values produce partially transparent elements.

Syntax

opacity: <number>;

Value Range:

  • 0 is fully transparent (invisible).
  • 1 is fully opaque (this is the default).
  • Intermediate values (e.g., 0.5) are partially transparent.

A Basic Example

The concept is really fairly simple, here's an example:

.box {  width: 10rem;  height: 10rem;  background-color: steelblue;  opacity: 0.5;}

This produces a box that is 50% transparent, which will allow the background or any overlapping elements (really 'under'lapping) to show through.


Interaction with Other Elements

An important feature of opacity is that it does not remove the element from the document flow, even when totally transparent (opacity: 0). Transparent elements still remain clickable and occupy space, unlike elements hidden with properties like visibility.

What this means is that if you want a fully transparent element that doesn't intercept user clicks for example, you need to also consider pointerevents, like this:

.transparent {  opacity: 0;  pointer-events: none;}.shown {  opacity: 1;  pointer-events: auto;}

Setting pointerevents: none will completely prevent user interaction with an element whilst it's also transparent.


Wrapping up

The CSS opacity property allows us to control the transparency of an element, which means we can then introduce subtle visual effects without altering the document structure or layout. If however you need to completely hide an element, consider the related visibility property.

Key Takeaways

  • opacity controls the transparency of an element, with values ranging from 0 (fully transparent) to 1 (fully opaque).
  • Transparent elements remain interactive and occupy space in the document.
  • Use pointerevents: none to disable interaction with transparent elements.

For scenarios where you need to entirely hide an element whilst preserving its space, read my article on CSS visibility.


Categories:

  1. CSS
  2. Development
  3. Front‑End Development
  4. Guides