Home > Back-end >  Why does px and em behave different in this case?
Why does px and em behave different in this case?

Time:03-12

Using 1em as margin-left, on my paragraph with fontsize xx-large, gives me more margin than using 16px. How is that possible when 1em equals 16px?

CodePudding user response:

You are confusing em and rem. As others already wrote, em uses the element's font-size, whereas rem uses the basic fontsize . That can be defined as font-size for the html tag. If it's not defined, it falls back to the browser setting, which by default is 16px most of the time (but can also be changed by the user in the browser settings).

CodePudding user response:

EM uses the Element fontsize. Because you have given font-size: xx-large on your paragraph the fontsize is not 16px but 32px.

CodePudding user response:

Using the em unit for margin will use the font-size from the element it is applied to. Unless that is exactly 16px, it will not match an explicitly 16px margin.

p {
  margin: 0;
  font-size: 20px;
}

.em {
  margin-left: 1em;
}

.px {
  margin-left: 16px;
}
<p >1</p>
<p >2</p>

CodePudding user response:

em uses font-size of element applied, so its px size is not constant. You can use rem unit, it always uses default font-size of browser(16px).

  • Related