Every CSS color system has an optional alpha component that can define a color’s level of transparency. For example, to produce a background color of red that is halfway transparent for a <div>
with an id
of genera
, we could write:
#genera {
background: rgba(255, 0, 0, 0.5);
}
Colors with alpha components are particularly useful for creating shadows and subtle gradients, but they can be applied anywhere that ordinary colors can, including borders and text.
When an alpha level is included, the color systems are referred to as rgba
and hsla
. These are not regarded as new systems, but as variants of rgb
and hsl
.
For rgba
and hsla
, the alpha level is measured from 0
to 1
, where 0
means “completely transparent” and 1 means “completely solid” or opaque. A floating point value for alpha between these numbers will produce a partially transparent color; an alpha value of 1
will produce a color that is exactly the same as the defined color without an alpha component.
As a floating point value, alpha can be written either with or without a loading zero. Generally speaking, the former (“0.3
”) is more readable. Note that writing an rgb
color definition (rather than rbga
) that includes an alpha component will not work; similarly, writing an rbga
color but forgetting to include an alpha component will fail to produce any color at all.
All modern browsers have support for alpha components in color, including IE 9+.
Hex with alpha?
It’s also possible to produce hex colors with alpha components, which are also stated as hexadecimal values:
#genera {
background: #ff000077;
}
The code above would produce a background color that is a halfway-transparent red. If the hex color is all “doubles”, it can also be shortcut:
#genera {
background: #f007;
}
alpha levels for hexadecimal colors are very new, and only currently work in Safari 10 and beta versions of other browsers, and thus cannot yet be used in production unless you’re using a compiler such as Sass or PostCSS that will convert #rrggbbaa
into its equivalent rgba
or hsla
definition.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/KzYpXw