W02 Learning Activity: CSS Units of Measurement
Overview
In this activity you will learn about the different values you can provide for CSS properties, such as an element's size or color.
Prepare
Numeric Values
In CSS, property length values are needed to provide layout and presentation control. There are two main types: absolute and relative. The absolute length, like 10px (pixels), is not relative to anything else and is typically the same size on most devices. Relative lengths, like 90%, are dependent on other items including the parent, sibling, or the size of the viewport.
Common length units include:
px: pixels, an absolute unit.%: a percentage of the size of the parent element.em: relative to the current font size of the element.rem: relative to the font size of the root (html) element.vwandvh: 1% of the width or height of the viewport.
Watch the following video:
▶️ CSS: Units of Measurement (4:47 minutes, 📄 Transcript)
Color Values
In addition to the numeric units used for sizes, CSS also allows you to specify colors in various ways. CSS color values for text, backgrounds, and wherever applicable can be coded by the following methods:
- keyword:
antiquewhite,burlywood,yellow,lightyellow, etc. - hexadecimal RGB (red, green, blue):
#faebd7
where the first two characters are the red value, the next two are the green value, and the last two are the blue value in hexadecimal (base 16) format. Each pair ranges from 00 to FF (0 to 255) - RGB:
rgb(250 235 215)or, with transparency,rgb(250 235 215 / 50%)
whereris a red value ranging from 0 to 255,gis a green value ranging from 0 to 255,bis a blue value ranging from 0 to 255, and the optional last value is the alpha (opacity) value ranging from 0 to 1 (0% to 100%) - HSL:
hsl(34 78% 91%)orhsl(34 78% 91% / 50%)
wherehis the hue (0 to 360),sis the saturation (0% to 100%),lis the lightness (0% to 100%), and the optional last value is the alpha value (0 to 1 or 0% to 100%)
You will also see an older syntax that uses commas and separate function names for transparency, such as rgba(250, 235, 215, 0.5) and hsla(34, 78%, 91%, 0.5). Both forms work in all browsers.
Activity Instructions
Answer the following questions about CSS value units/lengths.
- What is the most common absolute length unit for screens?
Help – Scroll down to Absolute length units to find the answer.
Check Your Understanding
px (pixels)
- Which CSS relative length unit is based upon the font size of the root element?
Check Your Understanding
rem
- Given a hexadecimal (base16) color value of #0e421c, what value is the Green level?
Check Your Understanding
42 in hexadecimal, which is 66 in decimal.
There are two hexadecimal values per color. First red, then green, and then blue. That is why there are six total characters with values in hex (0 to F).
Optional Resources
- CSS Values and Units – MDN
- Color Section – MDN
- Named Colors / Keywords – MDN