Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Control HTML Elements with Different CSS Units


    When working in CSS it's important to understand the difference between absolute units like pixels and relative units like em, percentages, and rem. Let's apply these to a H1 element and see how they are calculated by the browser.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: Let's go ahead and give our h1 a font size of 30 pixels, so they're 30 px, save and refresh. Using our DevTools, we can confirm that our h1 is now at a font size of 30 pixels. Pixels are referred to as absolute units, because they'll always be the same size regardless of any other related settings.

    With the font size declared, let's give it a padding of 2 em. Save and refresh. If we look at our h1, we can see it's got a bunch of padding around it. Em is referred to as a relative unit, because it depends on this font size here to calculate how much padding they give to it.

    If we look at the computed padding for this element, we'll see its associated pixels. That's because em goes off the font size. One em is going to be 30 and two will be 60.

    If we change our em to rem, and save and refresh, we'll see that our padding now sets 2 rem, and the computed padding is 32 pixels. This is because rems work exactly the same way as ems except for, it will go off with the default base font size and not the font size that's applied to the current element. The default font size is 16 pixels. That's why we get 32 pixels when using 2 rems.

    We can also use percentages inside of our CSS. We change our 30 pixels to 200 percent. Save and refresh. We'll see that our font size is now 32 pixels. That's because percentages are calculated after the parent size. For our font size, that's going to be the default size of 16 pixels, 200 percent of 16 is going to be 32. If we use the percentage on width or height, it would calculate the width or height, but the size of the parent's height and width.