How do you change the color opacity or transparency in CSS?

There are instances when you think it would be a great idea to change the opacity of the background color of a div without affecting the text, image, and other web properties present inside the same div of HTML and CSS.


What you usually do is specify background color in CSS using hex, i.e. Hexadecimal values like this:

.navbar {background-color: #ffffff;}

But if you use RGBA to specify background color in CSS, you can utilise its feature called alpha, i.e. RGBA is a short form for Red – Green – Blue – Alpha

What is RGBA:
RGBA color values are supported in IE9+, Firefox 3+, Chrome, Safari, and Opera 10+. RGBA color values are an extension of RGB color values with an alpha channel, specifying the object’s opacity. An RGBA color value is specified with rgba(red, green, blue, alpha). The alpha parameter is between 0.0 (fully transparent) and 1.0 (fully opaque).

So now you can tweak your code with RGBA CSS code with a fallback to RGB to something like this:

.navbar {
	background-color: rgb(255,255,255); /* RGBA Fallback to RGB to support old browsers */
	background-color: rgba(255,255,255,0.5); /* Background color white with 50% opacity */

Tip: The above code, with transparency and opacity, will delight the user with a good user experience. It allows the user to see what is behind the navbar while scrolling and navigating.

Now, using this technique, you can also change the text color by using the following code:

.h1 {
	background-color: rgb(0,0,0); /* RGBA Fallback to RGB to support old browsers */
	background-color: rgba(0,0,0,0.5); /* H1 HTML Heading tag with black color with 50% opacity */

Tip: The above code will look nice if the HTML Heading Tag happens to be on an Image or a background of a different color.

Hope it helps,

Thanks & Regards
Mandar Apte

Published by Mandar Apte

Mandar is a Mumbai-based multi-disciplinary designer with UX/UI, Logo, Symbol, and Brand Identity design expertise. He currently runs his Mudrkashar Linguistic Apple iPhone, iPad, and Mac app business in the heart of Mumbai city.

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.