When defining an HTML element’s size — whether it’s a font size, the width or height of div, or the margin and padding of any particular element, you can use relative units like rem or em, or you can use a fixed unit, like px. Rem and em units are growing more popular as an ever increasing number of sites are becoming mobile-friendly. Em units are especially mobile-friendly because they define the size of an element as it relates to its parent element. So for example, if your css looked like this:
- html{
- font-size: 2em;
- }
- p{
- font-size: .75em.
- }
The default font-size for your html would be 2em, which is the equivalent of about 32px. The font-size of your p elements would then depend on the font-size of their parent elements. So if the p element’s direct parent was the html or another element that inherited the html’s 2em font-size, the p element’s font-size would be 75% of 2em, or about 24px.
These relative units are particularly useful in mobile styling because they have the potential to seriously condense our media queries. Let’s say that the font-size of your html was set to 32px, the font-size of your h1 elements was set to 24px, and the font-size of your p elements was set to 16px, but you wanted all of these sizes to be bigger on a mobile device. If you’re using px, then you have to write new CSS for each of these elements in your media queries, like this:
- @media screen and (max-width: 500px){
- html{
- font-size: 48px;
- }
- h1{
- font-size: 32px;
- }
- p{
- font-size: 24px;
- }
- }
That’s a lot of extra code. If you use ems, changing the font sizes for mobile styling becomes as simple as writing one line in your media query. For this example, let’s assume that the font-size for the html is 1em — the default size.
- @media screen and (max-width: 500px){
- html{
- font-size: 1.5em;
- }
- }
This way, all you have to do is define the html’s font-size in ems, and as long as the other html elements have font-sizes that are defined using ems, they will automatically scale accordingly.
There is also the option of using the rem unit (root em unit) in place of the em. The difference between rem and em is that em is always relative to the font-size of its most direct parent element, while rem is only relative to the root font-size, meaning the font-size of the <html> element.