Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Susitha Herath Mudiyanselage
Susitha Herath Mudiyanselage
4,957 Points

Why same width of em unit display different sizes?

Can some one please explain why i see different sizes in the browser even when i set 10em for each element's width?

html:

<h1 <div <p </div <h2

/css/

html{
    font-size: 1em;
}

h1{
    width: 10em;
    background-color: yellow;
}
h2{
    width: 10em;
    background-color: lightgreen;
}
.box{
    width: 10em;
    height: 3em;
    background-color: coral;
}
p{
    background-color: hotpink;
    width: 10em;
}

3 Answers

The above commenter is correct in saying that em is about context; you must consider the context of the parent. You can calculate the target size by using the target / context = result formula. Also, consider using the rem unit which is always relative to the base font size (16px or whatever you set). The rem unit enjoys fairly good support among browsers (not below IE9 or Opera Mini, though).

em is always about the context. in your hierarchical example h1 is based on the 16px base font size. (if not changed to another value). the child elements of h1 don't have 16px as context but h1 as context. and so on.