Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Honor user's transparency setting in CSS

When you’re building a website, you might be tempted to use a transparent background for some elements. For instance, you may want to use a transparent background for the navigation bar or the header of the website.

But not everyone likes transparency. Some people may prefer to have a solid background instead of a transparent one because it’s easier to read the text on a solid background and also, less distracting.

In operating systems like macOS, you can enforce transparency settings for all the applications by going to System Preferences > Accessibility > Display. Then Click on the option to “Reduce transparency” to have a semi-transparent background in the areas of the desktop and apps.

The good news is, that you can honor this transparency setting in your website as well using CSS.

A new media query called prefers-reduced-transparency has been introduced in CSS which you can use to detect if the user has enabled the transparency setting in their operating system.

.translucent {
  opacity: 0.4;
}

@media (prefers-reduced-transparency) {
  .translucent {
    opacity: 0.8;
  }
}

As you can tell, the prefers-reduced-transparency media query is used to detect if the user has enabled the transparency setting in their operating system. If they have, the opacity of the element will be set to 0.8 instead of 0.4 which is the default value.

This way, you can honor the user’s transparency setting in your website and make it more accessible for them.

The only caveat is, that this media query is currently only supported in Chrome 118 and above. So, the rest of the browsers still need to catch up. But it’s a good start nevertheless.

Read more about this media query in its spec here.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?