Why you should use em instead of px in CSS?

In this learn about the CSS units (em, px, others), and why you should use em instead of px in CSS. Learn with the help of examples. By Apurva Mathur Last updated : July 15, 2023

Let us first learn about the CSS units.

CSS Units

CSS units can be classified into two major categories:

  • Absolute
  • Relative

CSS Absolute Units

These are called the fixed-length units; this is not accepted as best practice when you are working on the screen, because screen size varies a lot. We can these units when the responsiveness of the site is not our target.

The absolute units are as follows:

  • cm (centimeter)
  • mm (millimeter)
  • in (inches)
  • pt (points)
  • pc (picas)
  • px (pixels)

CSS Relative Units

Relative units are known to be the best practice when the responsive site is our target. These units scale relative to the window size. They specify length which is relative to another length. These units render between different units.

Some relative units are as follows: -

  • em
  • ex
  • ch
  • rem
  • vh
  • vw
  • vmin
  • vmax
  • %

Why you should use em instead of px in CSS?

The answer to our question is really simple and already defined in the above definitions. Since px is a part of absolute units so it is not considered good for making websites because whenever we are making any website we should always keep in mind the responsive of the site. px is not scalable. Change in the value of another element does not affect the value of absolute units. The value assigned is fixed irrespective of the user settings.

Whereas em is a part of relative unit it allows scalability within the context of a specific design element because of which when we are working on the responsiveness of the site em unit is widely used. We use em when we specifically want the size of something to depend on the current font size.

CSS Examples »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.