Reputation: 69
I have some serious problem understanding the code:
<!DOCTYPE html>
<html>
<head>
<style>
body{
font-size:16px;
}
p {
margin: 0 0 1em 0;
font-size: 2em;
line-height: 1em;
}
</style>
</head>
<body>
<p>Sample Text</p>
</body>
</html>
I understand that the font size is now 32px because I put 2em which will be twice of 16, but why is the margin-bottom and line-height 32px even though its 1em?
Upvotes: 2
Views: 1253
Reputation: 7080
In your case, you should use rem
instead of em
.
Take a look here.
em
is relative to the font-size of its nearest parent while rem
is relative to the root font-size.
I'd like to think "r" of rem
as the "root em". And the root mean the html
not the body
element.
console.log("padding of div em : " + window.getComputedStyle(em).padding);
console.log("padding of div rem : " + window.getComputedStyle(rem).padding);
html {
font-size: 10px;
}
div.parent {
font-size: 20px;
}
div.child {
border: 1px solid black;
margin: 5px;
}
#em {
padding: 1em;
}
#rem {
padding: 1rem;
}
<div class="parent">
<div id="em" class="child">1em</div>
<div id="rem" class="child">1rem</div>
</div>
Upvotes: 3
Reputation: 2261
Since you are using em as font size unit, It is relative to the immediate parent or the same element which is having font-size declared. Here your <p>
has font size of 2em(that means 32px) So the line height and margin is now considering 32px as its base value and em is calculating based on this new value.
But if you are using rem as the unit, it will always take body/html font size as its base value.
Upvotes: 2