CSS Units

avatar

NaN years ago

CSS Units

CSS Units determine the size of a property you're setting for an element or its content.

Here is an example of a CSS unit:

font-size: 16px;


The font-size is the property, 16px is the value of the property. Px is a css unit called pixel.

CSS Units can be categorized by Absolute Units and Relative Units:


ABSOLUTE UNITS


RELATIVE UNITS

  • Fixed Value
  • Scaled Values
  • does not scale when the screen size changes
  • they scale relative to something else


  • Ex: px (pixels)


  • Ex: Relative to their parent (%), viewport (vw, vh), font size (em, rem)
  • We can create responsive webpages with the aid of relative units. Let's talk in depth about the most prevalent units.


Relative to their parent(%):

CSS FILE

.App .Parent {

  background-color: blue;

  width: 100%

}

.App .Child {

  background-color: yellow;

  width: 50%

}


  • In the example, inside a parent div, we have a child div. The child div will be 50% of the parent div.

Viewport (vw, vh)

  • The viewport is the user's visible area. Whether it is a desktop or a smartphone. vw stands for viewport width. vh stands for viewport height. For example: 100vh is 100% of the viewport height (100% height of a smartphone or 100% height of a desktop).

Font size (em, rem)

  • em - are relative to the font size (always x times of the parent). For instance, 1em is equal to the font-size of the parent. 2em is twice the font size of the parent. 3em is 3 times the font size of the parent.

HTML:

<div className="Parent">

  <h1>Main Title</h1>

  <h2>Next Title</h2>

</div>


CSS:

.App .Parent {

  font-size:16px

}

.App .Parent h1 {

  font-size: 3em;

}

.App .Parent h2 {

  font-size: 2em;

}


In our Parent div we have a font size of 16px. In our h1 we have a font size of 3em which is 3 times the font size of its parent with 16px. Therefore our h1 has 48px (16px*3em) and our h2 has 32px (16px*2em).




  • rem - are relative to the roots html font size. If the root html is not defined then it will be equal to the default font size of the browser (16px usually). This is a more preferred method.

CSS:

html {

  font-size: 20px;

}

.App .Parent h1 {

  font-size: 3rem;

}

.App .Parent h2 {

  font-size: 2rem;

}



approvedApproved by experts
Advance Topics

Neuton's Mission

We are a team of young and enthusiastic people who are passionate about education and want to help students to learn the skills they need to succeed in life. If you want to support us, please join our community.

phonephonephonephonemail