Andy
Andy

Reputation: 1432

EM versus REM in structural content

The following code illustrates my question about using EM's instead of REM's in formatting structural content (like width, height, borders width, etc.)

The first example using EM's produces a different box result than the other two. Why is that, given that the font size is as expected and the style is inherited from the html style (although I'm guessing not given it doesn't look the same as the REM style).

https://jsfiddle.net/AndyMP/L7jshu9c/11/

html {
  font-size: 1em; /* 16px */
}

.box1 {
  width: 10em;
  border: solid .25em black;
  font-size: 1.5em;
}

.box2 {
  width: 10rem;
  border: solid .25rem black;
  font-size: 1.5rem;
}

.box3 {
  width: 160px;
  border: solid 4px black;
  font-size: 24px;
}
<div class="box1">Ems</div>

<div class="box2">Rems</div>

<div class="box3">Pxs</div>

Update: I may be answering my own question here, but it seems as though the font-size between the div tags is set first and then the width and border elements of that div are sized based on that font size. Maybe somebody can confirm why that's the case...

Upvotes: 1

Views: 158

Answers (1)

Arno Tenkink
Arno Tenkink

Reputation: 1528

Nice question, the 'r' in rem stands for 'root'. em childs inherits the parents size and calculates the extra given to it. When using rem it only calculate what the root in this instance html gives it.

Why does this give a different result?

Because you set your box to 1.5em. The font-size gets to 24px so your box width becomes 240px.

The rem variant still stays with the root value of 16px so it stays at 160px.

See sample below.

html { font-size: 10px }

.em { 
  padding: 15px;
  font-size: 1.4em;
  border: 1px solid grey;
}

.em div {
  font-size: 1.4em;
}

.rem { 
  padding: 15px;
  font-size: 1.4rem;
  border: 1px solid grey;
}

.rem div {
  font-size: 1.4rem;
}
<html>
<div class="em">
  <strong>EM</strong>
  <div>layer 1
    <div>layer 2
      <div>layer 3</div>
    </div>
  </div> 
</div>
<div class="rem">
  <strong>REM</strong>
  <div>layer 1
    <div>layer 2
      <div>layer 3</div>
    </div>
  </div>
</div>
</html>

Upvotes: 1

Related Questions