Basics of CSS Units

Units in CSS

In our daily lives, we use units to measure a variety of things, such as length, volume, and mass. And there are numerous ways to measure them, which are referred to as units. In CSS, multiple units are used to measure the dimensions of many Element properties such as padding, border thickness, width, and so on. Below is the description of how units can be used with the compatible CSS property.

css-query-selector{
width:8px;
}

In the code above, I have used px(pixel) which is one of the most commonly used CSS units.

Types of Units

Units in CSS are divided into two parts

  1. Absolute
  2. Relative

Absolute units are like the selfish kids in the family who don't care about their surroundings, or in technical terms, those who don't care about the window size or parent elements. Types of Absolute Units: cm,mm,Q,in,pc,pt, and px.

px is the only widely used absolute unit. I never had to use other absolute units in my one and a half years as a front-end developer. The majority of these other units are used for printing output on paper rather than for screens/devices.

Relative units are concerned about their parents and siblings; in technical terms, they are relative to other length properties such as the parent element's font size, or viewport size. Using these units makes the life of a front-end developer easier.

Knowing these units and when and why to use the particular relative units can decrease your stress levels and frustrations.

Types of Relative units : em,ex,ch,rem,vw,vh,vmin,vmax, and %.

These units are all related to various properties, elements, and conditions. % refers to the parent element, whereas rem refers to the root element's font size. vw refers to the width of the viewport, while vh refers to the height of the viewport. Another important and widely used relative unit is em, which is a multiple of the element's font size and is relative to it.

To read more about this, check out these links: MDN Docs- Values and Units