Absolute length
The default font size for HTML CSS is 16px, but we often do not want to use default values. This is because setting a hard value for pixel size will not respect browser font-size settings, nor will it follow screen sizes.
Although there are many absolute unit lengths available, the most commonly used one is px, or pixels. A pixel is defined as 1/96th of an inch, although it really refers to a single pixel on a particular screen.
A good place for specific pixels is in decorations - such as a border around text, or the borders of a table, for instance, since those do not necessarily need to scale up and down with user preference.
Relative length
Percentage
Percentages are a percent of another value. They are often not used it fonts, though - it is used for element sizing.
The percentage value of an element will be a percentage of its parent element size. For example:
header {
width: 50%;
}
h1 {
width: 50%;
}This means the h1 will be 50% of the width of header, while the header is 50% of the document - effectively making h1 25% of the document.
rem
Rem is the commonly used unit of measure for font size. The default is 1rem. Note that this means “1 root em” - meaning a 1 is 100% of the root size set by the browser. Thus, 2rem means everything will be twice as big as the default.
Note that unlike percentage, rem measurements are relative to the browser settings (unless we set a base font size in the html element).
rem vs em
rem is comparing to the root of the element or page, while em will simply look at the parent.
Using rem is preferred for typography, but em will often be used for padding and the like:
h1 {
font-size: 3rem;
padding: 1em;
}This declares that the size of the font is 3 times the default set by browser or document. The padding, in this case, is also equivalent to 3 because the 1em is “inheriting” or comparing to the element itself.
ch
ch is a measure based on 0 - that is the width of the 0 character itself. This allows us to implement things like setting a maximum number of characters per line.
vw/vh
vw refers to “view port width”, which is the size of the page we are looking at. A common problem is setting 100vw to try and capture the whole page, since it does not account for a vertical scroll-bar when there is a lot of content. To avoid this we can use percentage width of 100% to eliminate the problem (although this is the default anyway)
A usecase of vw and vh is when we want the body element to take the entire size of the page, regardless of whether there is content or not.