Units
Mostly in this guide, we’ll be using pixel units. A pixel is a single square of color on a screen. Until recently, a pixel was made up of three sub-pixels — one red, one green and one blue. Each of the sub-pixels adds together to make different colors. However, more recently, retina screens have been able to double the amount of sub-pixels both down and across the screen, so on retina screens like the iPhone, there are actually 12 sub-pixels (four red, four green and four blue). There are other types of unit that we’ll be using in the guide.
In CSS, a pixel unit is defined as a number (positive or negative) that ends with “px”:
header {
font-size: 16px;
}
Percentages
We can also use percentages in our CSS instead of pixel units. These are mainly useful in layouts:
section {
width: 75%;
}
Em units
An em unit is a size relative to the current font size of that tag. By default, the font size would 16px, so we could use em units instead of px if we’re unsure what pixel size to use but want to make it relative sized:
header {
font-size: 2em;
}
By default, that would be twice 16px (32px). However, if we have something inside the header and use em units, it would be now based on 32px sizes:
header h1 {
font-size: 1.5em;
}
The pixel size for this <h1> tag would be 1.5 times 32px (not 16px), so 48px large in pixel units.
Rem units
Similar to em units, rem units are based on the current font size of the page (not the current tag). In the last example, the header size would be
32px if we had “2em” or “2rem”, but the <h1> tag would be 24px if we were to use “1.5rem” instead of “1.5em”
vw, vh, vmin and vmax
We can base our sizes on the “viewport” — essentially the part of our page that the browser can currently see. If our unit is “1vw”, this is 1 percent of the viewport width, so if our browser is 1200px across, 1vw is 12px. “vh” is 1 percentage of the viewport height — so if we can only see 800px of our page in the browser, 1vh is 8px.
Sometimes we might not know how wide or tall our user’s browsers are, so using “vw” and “vh” units can work well. For instance, having a section at exactly the height of the browser could be useful for an intro to the page:
section {
height: 100vh;
}
The “vmin” units look at the sizes of “vh” and “vw” and see which one of the two is the smallest. The “vmax” unit does the same, except looking for the larger of “vh” and “vw”.