CSS hsla() Function
The CSS hsla()
function can be used to add transparency to a color when using the HSL model. It allows you to specify a color value by specifying the hue, saturation, and light components of the color, as well as an alpha layer.
The hsla()
function is based on the HSL color model. HSL (which stands for Hue Saturation Lightness) is a hue-based representation of the RGB color space of computer graphics.
The hsla()
function accepts the HSLA value as a parameter. The HSLA value is provided as a comma-separated list of four values — the three HSL values (which provide the hue, saturation, and light components respectively), and a fourth value, which provides the alpha channel.
Here's an example:
The first of the four values — the hue component — represents an angle of the color circle.
You can specify the value as an angle in degrees (e.g. 180deg
) or simply as a number (e.g. 180
). For example, if you look at the color circle, blue is at 240 degrees, so it could be written as either 240deg
or 240
.
The second value is expressed as a percentage. It represents the amount of saturation in the color. For example, 100%
is fully saturated (more colorful and intense), while 0
is a fully-unsaturated gray.
The third value is also expressed as a percentage. It represents the amount of light in the color. For lightness, 50%
is the "normal" setting, while 100%
is white and 0%
is black.
The fourth value is the alpha value. It determines how transparent the color is. A value of 1
is fully opaque, while a value of 0
is fully transparent. A value of 0.5
is semi-transparent.
Example
Here's a working example of using the hsla()
function to define colors for a web page.
Tweak the HSLA values to see the effect it has on the output. For example, change the alpha setting to see how it changes the transparency of its element.
Examples of Alpha Variations
Here's an example of the same color repeated multiple times (across a background image), but each one with a different alpha value.
All other values are the same (i.e. the hue, saturation, and lighting are the same across all rows), only the alpha channel changes.
This demonstrates that the background image becomes less visible as the alpha value increases (the stars are the background image).
Blue
hsla(240, 100%, 50%, 0) | |
hsla(240, 100%, 50%, 0.1) | |
hsla(240, 100%, 50%, 0.2) | |
hsla(240, 100%, 50%, 0.3) | |
hsla(240, 100%, 50%, 0.4) | |
hsla(240, 100%, 50%, 0.5) | |
hsla(240, 100%, 50%, 0.6) | |
hsla(240, 100%, 50%, 0.7) | |
hsla(240, 100%, 50%, 0.8) | |
hsla(240, 100%, 50%, 0.9) | |
hsla(240, 100%, 50%, 1) |
Setting the HSL Part
The HSL color model is much more intuitive for setting colors than the RGB model. Especially once you know how HSL works.
I've written about the hsl()
function, which explains the HSL part of the hsla()
function in more detail than what's written here. Check it out if you're not sure how to set amd adjust the base color.