Whats the difference between px, em, rem and others in CSS

Often you will see font sizes and measurements in your CSS using px, which you probably know stands for pixels. But there are other ways of setting the size of fonts and other elements. Even if you only use WordPress at a beginner level. It is inportant to understand the differences in these ways of measurements, even if you can not use them all to their full extent. So, lets look at them in turn, and how you will probably see them in your style sheets.

p {
font-size: 12px;
margin-borrom: 20px;

Will give your paragraph text a size of 12pixels and a margin at the bottom of 20px. All easy to follow.

Othertimes you will see measurements like 1em.  The  em is relative to the font size of its direct or nearest parent. 1em defualts to the standard pixel size of 16px.

.sidebar {
font-size: 1em;
margin-bottom: 1.5em;

But what if we mix them up. The em measurement will always take its lead from the nearest px size, so it can change.

h1 { font-size: 2em; /* 1em = 16px */ 
margin-bottom: 1em; /* 1em = 32px */ } 
p { font-size: 1em; /* 1em = 16px */ 
margin-bottom: 1em; /* 1em = 16px */ }

This could not give the same sized margins as h1 is a bigger font size. Or you could have text in a block which has a different font size. This can be useful for keeping blocks of code relative, but in other cases it could make a big mess of your layout. Take this example to see how a block changes things.

See the Pen Px Rem and EM by john (@wpbusinessclub) on CodePen.0

In the example I have also added a new measurement. 1rem. This is the Root Em. It relates to the root element of the document. So this is a more absalute reference. It is 1em of the font size of html, whereever it is used.  By default you should expect this value to be 16px.

Have a look again at the example in codepen, you can open to edit it, for a btter look. You see how the em is larger in the second block becuase the div parent has larger font size. This can be a blessing or a curse depending on the situation. The 1rem stays the same.

Where I find this most useful is where I set a maring around some text of say 1.5em. If I decide to change that font size, in further development, or in a media query when the screen changes. The margin is going to change as well in proportion.

Just to finish the list. These are useful for planning the overall layout.

  • We also have vw and vh. A vw is 1% or 1/100th of the screen readers window, and vh is 1% of the height.
  • vmin is the smallest of either vw and vh.
  • vmax is the largest.