CSS units are used to define sizes, spacing, and layout in web design. Understanding these units helps you create responsive and well-structured websites.
Pixel px
Pixels are fixed units. They represent a specific number of dots on the screen. This means the size will not change based on screen size.
Example
font size 16px will always stay 16 pixels on any device
Use px when you want precise control over size such as borders or small elements
Percentage %
Percentage units are relative to the parent element. This means the size depends on the size of its container.
Example
width 50 percent means the element will take half the width of its parent
Use percentage for flexible layouts and responsive design
em
The em unit is relative to the font size of the parent element. It scales based on the surrounding text.
Example
If parent font size is 16px then 2em equals 32px
Use em for scalable spacing and typography but be careful as it can compound in nested elements
rem
The rem unit is relative to the root element which is usually the html tag. It provides more consistent sizing than em.
Example
If root font size is 16px then 2rem equals 32px regardless of parent size
Use rem for consistent and predictable layouts across the whole website
vh
Viewport height is based on the height of the browser window. One vh equals one percent of the viewport height
Example
height 100vh makes an element take the full screen height
Use vh for full screen sections and modern layouts
vw
Viewport width is based on the width of the browser window. One vw equals one percent of the viewport width
Example
width 100vw makes an element span the full width of the screen
Use vw for responsive widths and layouts that adapt to screen size
Summary
Pixels are fixed and best for precise control
Percentage is relative to parent and good for flexible layouts
em is relative to parent font size and useful for scalable design
rem is relative to root and best for consistency
vh and vw are based on screen size and ideal for responsive design
Practice Task
Create a simple webpage and apply different units to text boxes and sections. Try resizing the browser to see how each unit behaves.