0

I defined a button and a div and their size once with unit of measurment px and again with em. why when i defined their size by px ,div and button is equal but when i defined their size by em button is smaller than div?

   .div1 {
       width: 102px;
       height: 102px;
       border: 1px solid blue;
  }
    .button1{
       width: 102px;
       height: 102px;  
       border: 1px solid red;
  }
    .div2 {
       width: 10em;
       height: 10em;
       border: 1px solid blue;
    }
    .button2{
       width: 10em;
       height: 10em;  
       border: 1px solid red;
    }
 <div class="div1"></div> 
 <button class="button1"></button>

 <div class="div2"></div> 
 <button class="button2"></button>
reza n
  • 59
  • 3

2 Answers2

0

em is based on the font-size and a button has a default font-size applied by the browser equal to 13px so the button will have a size equal to 130px and the div a size equal to 160px since the default font-size for the document is 16px

Change the font-size of the button and they will have the same size:

.div1 {
  width: 102px;
  height: 102px;
  border: 1px solid blue;
}

.button1 {
  width: 102px;
  height: 102px;
  border: 1px solid red;
}

.div2 {
  width: 10em;
  height: 10em;
  border: 1px solid blue;
}

.button2 {
  width: 10em;
  height: 10em;
  font-size: 16px;
  border: 1px solid red;
}
<div class="div1"></div>
<button class="button1"></button>

<div class="div2"></div>
<button class="button2"></button>

enter image description here

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • Good point. Plus, if you are using anything like Bootstrap, Material or jQuery UI (and who-knows-what-else), you have to take into consideration that other default values for button font sizes and padding could get applied. Just saying. – Shawn Spencer Oct 21 '19 at 15:54
0

Pixels (px) are a fixed size unit, unlike ems that are relative to the element font-size. Your div and your button are probably a different font-size value, probably by default if you have not defined it somewhere.

If you explicitly set the font-size to be equal, they will both have the same size:

.div1 {
  width: 102px;
  height: 102px;
  border: 1px solid blue;
}

.button1 {
  width: 102px;
  height: 102px;
  border: 1px solid red;
}

.div2 {
  font-size: 10px;
  width: 10em;
  height: 10em;
  border: 1px solid blue;
}

.button2 {
  font-size: 10px;
  width: 10em;
  height: 10em;
  border: 1px solid red;
}
<div class="div1"></div>
<button class="button1"></button>

<div class="div2"></div>
<button class="button2"></button>
giuseppedeponte
  • 2,366
  • 1
  • 9
  • 19