CSS offers a variety of units, such as %, px, em, rem, vw, and vh, each serving a unique purpose.
Choosing the right unit for different circumstances is crucial for creating a
responsive and user-friendly design.
This guide will provide general best practices to help you decide which CSS
units to use in various situations.
Font Sizes: Use 'rem'
For font sizes, it’s best to use 'rem'. This unit is relative to the
font size of the root element (usually the <html> element), which by
default is 16px.
Using 'rem' allows your design to adapt to the user’s system and browser
preferences, whereas 'px' values are fixed and not easily overridden.
To simplify the conversion from 'px' to 'rem', set your
<html> element’s font size to 62.5%. This makes 1rem equal to 10px,
making calculations straightforward.
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 and Height: Use %
and 'min-height'
In most cases, using percentages (
%
) in combination with a
max-width
property is ideal for creating responsive
layouts.
Avoid setting fixed heights; instead, use
min-height
to
allow elements to adjust naturally to their content.
.container {
width: 50%;
max-width: 1000px
}
Padding and Margin: Use 'rem' and 'em'
When setting padding and margins, use '
rem'
for consistent
values across your design.
If padding and margins need to scale with the font size, use
'
em'
.
For example, '
em'
is often used for button padding,
ensuring it grows and adjusts along with the font size.
.btn {
display: inline-block;
text-decoration: none;
background: #000;
color: #fff;
padding: 1em;
font-size: 2rem;
}
General Guidelines
-
Use '
rem'
for font sizes for better adaptability to user settings. -
Utilize
%
andmax-width
for responsive widths. -
Prefer
min-height
over fixed heights to allow content to grow naturally. -
Choose
rem
for consistent padding and margin, and 'em'
when these values should scale with the font size.
Follow our blog for usefull content related like web development, coding and free udemy course
If you like this content: Buy me a coffee