Em Unit in 2 mins!

Em Unit in 2 mins!

ยท

2 min read

Table of contents

Heyy all!

We have learned PIXELS & PERCENT UNIT...Now it's time to learn about the easiest unit in CSS and that is Em.

Em

What is an em unit in CSS?

  • Now we can pronounce "Em" as "m"

  • It's super simple and easy: It's just about MULTIPLICATION...Lemme show you!

HTML CODE ๐Ÿ‘‡

HTML, XML

<!-- We've made 1 div and inside it we have another one, there are IDs too! -->

 <div id="box1">box1
   <div id="box2">box2</div>
 </div>
  • There is a box1 and inside it we've box2 and we have named them as box1 and box2...

CSS CODE ๐Ÿ‘‡

CSS

#box1{
    width: 300px;
    height: 300px;
    background-color:rgb(255, 146, 95);
    font-size: 20px;
}

#box2{
    width: 50%;
    height: 50%;
    background-color: rgb(250, 253, 104);
    font-size: 1em;
}
  • In this ๐Ÿ‘† case we've targeted our box1 and we've set the width: 300px; and height: 300px; and added some background-color It's a normal square...After that, we set the font-size: 20px;

๐Ÿ‘‡

  • Then we've targeted box2 and set the width to 50% of the box1's width, which is 150px same as the height of 150px. Added some background color and then our em unit arrives...What is 1em?

๐Ÿ‘‡

  • How does em unit work?

  • In this case, EM is relative to its parent's font size like we have the font size as 20px so If I write box2 ---> font-size: 1em; then it'll be Multiplied by 1...

  • What is 20 * 1 = 20px! Both sizes will be the same as 20px...

OUTPUT ๐Ÿ‘‡

  • If I write 2em then it'll be 20 * 2 = 40px...

  • 2 times of the parent's font size...

  • The box1 will remain at 20px and box2 will be at 40px...

CSS

#box1{
    width: 300px;
    height: 300px;
    background-color:rgb(255, 146, 95);
    font-size: 20px;
}

#box2{
    width: 50%;
    height: 50%;
    background-color: rgb(250, 253, 104);
    font-size: 2em;
}

OUTPUT ๐Ÿ‘‡

As you can see box 2's size is increased to 40px! It's Super easy!

Little Challenge:

  • Set the font size of box1 to 30px and make box2's size half of box 1's size In short you have to make box 2's size 15px...

Hopefully, you're clear with the EM unit in CSS!

ย