Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Control HTML Elements with Different CSS Units

    Tyler ClarkTyler Clark

    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.

    cssCSS
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    Instructor: 00:00 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.

    00:21 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.

    00:38 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.

    00:48 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.

    01:15 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.

    Discuss

    Discuss