The Twilight Zone

New web developers and designers often get rgba (and its hsla equivalent) confused with opacity, using them interchangeably until they come up against a visual result that makes no sense.

This is understandable, as both opacity and the a component in rgba refer to the same quality: the level of transparency. However, their application and effect is very different:

  • one (opacity) is a property; the other is the component of the value of a color property, such as background-color, box-shadow-color, or border-color.
  • Most importantly, opacity affects the entire element it is applied to, whereas rgba affects only one aspect.

opacity, can be thought of as a “fade out” effect for elements. As an example, let’s overlap two div elements with absolute positioning. Both divs will have white text. The first will have a dark blue background. The <div> on top will have a black background, and contain an image. First, the HTML:

<div id="lower">
	<p>There is nothing wrong with your television set. 
	Do not attempt to adjust the picture. 
	We are controlling the transmission.
	We will control the horizontal, we will control the vertical.
</div>
<div id="upper">
	<p><img src=the-twilight-zone.png alt="The Twilight Zone">
	We can change the focus to a soft blur or sharpen it to crystal clarity. 
For the next hour, sit quietly and we will control all that you see and hear.
</div>

Then the CSS:

body { 
	background: #444;
}
div {
	width: 20em;
	padding: 3em;
	position: absolute;
	border: 5px double #000;
	color: white;
}
div p {
	margin: 0;
	text-align: justify;
}
div#lower {
	background-color: rgb(0, 0, 127);
}
div img {
	width: 200px; 
	height: 150px;
	float: right;
	margin-left: 3em;
	margin-bottom: 3em;
}
div#upper {
	left: 18em;
	top: 8em;
	background-color: rgba(0, 0, 0, 1);
}

rgba 50%We’ll lower the alpha value for the upper div halfway to 0. Note that the text, border and image remain unaffected by this change; the only difference, as we would expect, is to the background colour of the upper div.

Taking the alpha component all the way to 0 for background-color would mean that it would be immaterial what values we put in for red, green, or blue; the background-color would, under this condition, always be fully transparent.

div#upper {
	left: 17em; top: 7em;
	background-color: rgba(255, 255, 0, 0.5);
}

opacity 25%Let’s set background-color back to the conditions we had at the start and introduce opacity. Set to a value of 1 under our initial conditions, there will be no difference. Set to 0.25, however, produces a significant change. As you can see to the left, the entire div, including the background colour, paragraph content, border and image, is now halfway transparent. This is, obviously, a very different effect.

div#upper {
	left: 19em; top: 9em;
	background-color: rgba(0, 0, 0, 1);
	opacity: 0.25;
}

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.