There are many units in CSS, such as %, px, em, rem, vw, vh, etc. Each unit has a specific usage.
How to pick which css units to use in different circumstance, in this article I am going to talk about the best generalizations.
Before we dive in, I want you to remember this is just rule of thumb, It is just for helping you choose which unit in different situation.
Font Size
We'd better use rem for font size, it is relative to the font size of our root element which is our html element, html element's font size is default to 16px.
Why we use rem rather than px? Because rem is adapt to the user's system and browser preferences, px is locked thing and not easy to be override.
The problem is rem is based on 16px by default, it is not easy to convert px to rem. We can set html element's font size to 62.5% to make it easy.
10px = 0.625rem
12px = 0.75rem
14px = 0.875rem
16px = 1rem (base)
18px = 1.125rem
20px = 1.25rem
24px = 1.5rem
30px = 1.875rem
32px = 2rem
html {font-size: 62.5%;/*10 ÷ 16 × 100% = 62.5%*/}
body {font-size: 1.4rem;/*1.4 × 10px = 14px */}
h1 { font-size: 2.4rem;/*2.4 × 10px = 24px*/}
Width
In the most situation, % in combination with a max-width is the best choose.
.container {
width: 50%;
max-width: 1000px
}
Height
In the most situation, you don't need set fixed height, use min-height instead.
Padding and Margin
In the most situation, use rem or em.
If your padding and margin is consistent use rem, if it is base on font size use em.
For example, we always use em for button padding, it will grow and adjust along with font size.
.btn {
display: inline-block;
text-decoration: none;
background: #000;
color: #fff;
padding: 1em;
font-size: 2rem;
}
If you change font-size bigger, the padding will grow too.
Media Query
We use em for media query break point, check out this article for detail, https://zellwk.com/blog/media-query-units/
Other Rules
px only for little things like shadows, borders etc.
This article is based on this youtube video.
https://www.youtube.com/watch?v=N5wpD9Ov_To
Top comments (0)