CSS Units: Which Ones To Use And Avoid
An explanation on CSS units with examples to get you going
--
Since there are so many different units in CSS, it can be quite overwhelming. Most developers know how to work with pixels and percentages, but there are many more CSS units that can be used. Some of the CSS units that we will handle in this article are em, rem, fr, ch, vw and vh. You will learn which CSS units you should be using and why you should be using them. And you will also learn why you should not use certain units.
The units
Let’s start by going over each unit and explain where it’s specifically good for.
Pixels
Pixels are the basic building block for everything in CSS. Strangely enough, pixels shouldn’t be the unit of choice most of the time. Pixels are very straightforward, they say what they are going to do.
Take a look at the example below. This will render a 500px block with a red background that has a 14px font-size paragraph in it. If you wanted to make the div a little smaller, all you have to do is change the width to 250px, for example. You want the font-size a little bigger? No problem, just change the font-size to 16px.
<div>
<p>This is some text..</p>
</div>div {
background-color: red;
width: 500px;
}p {
font-size: 14px;
}
See how easy it is to change the styling with pixels? Pixels are very straightforward. And because of that, it is very tempting to use them. This will bite you if you continue to use pixels throughout your entire application. This is because pixels are really bad for accessibility. An easy example to demonstrate this is by changing the font-size in your browser. If you change the font-size nothing will actually happen with the font-size in your application. That is because we have set the font-size to 14px, no matter what. The CSS that we have defined will not respect the font-size setting of the browser. What pixels are good for is when you want something to look exactly the same width and height despite the user's browser settings. A good use case for pixels is when you are defining a border. You probably want that border to always be the same. But most of the…