feat(curriculum): add interactive examples to em and rem lesson (#62955)

Co-authored-by: Huyen Nguyen <25715018+huyenltnguyen@users.noreply.github.com>
This commit is contained in:
Diem-Trang Pham
2025-10-22 18:42:29 -05:00
committed by GitHub
parent 99d91a1219
commit 0d44fff1ff

View File

@@ -5,7 +5,7 @@ challengeType: 19
dashedName: what-are-ems-and-rems-in-css
---
# --description--
# --interactive--
In the previous lesson, we learned about absolute length units like pixels. While absolute units can be helpful in certain situations, there will be times when you want to use relative units.
@@ -15,16 +15,15 @@ In this lesson, we will learn about two relative units: `em`s and `rem`s.
To better understand how this works, let's take a look at an example:
:::interactive_editor
```html
<link rel="stylesheet" href="styles.css" />
<p class="para">I am a paragraph element</p>
<div class="blue-box"></div>
```
For the HTML, we have a paragraph and `div` element. The paragraph element has a class of `para`, and the `div` element has a class of `blue-box`.
Here is the accompanying CSS:
```css
.para {
font-size: 20px;
@@ -36,9 +35,15 @@ Here is the accompanying CSS:
background-color: blue;
color: white;
padding: 10px;
width: 100px;
height: 100px;
}
```
:::
For the HTML, we have a paragraph and a `div` element. The paragraph element has a class of `para`, and the `div` element has a class of `blue-box`.
For the `para` class, we set the `font-size` to `20px` and the `margin-bottom` to `1.5em`. This means that the margin will be 1.5 times the font size of the paragraph element. `1.5em` results in 30 pixels of margin at the bottom of the paragraph. We have also set a `border` of `2px solid red` so you can see the margins better.
For the `blue-box` class, we set the background color to `blue`, the text color to `white`, and the `padding` to `10px` on all four sides.
@@ -63,6 +68,14 @@ By default, the font size of the `html` element is `16px`. If the user increases
Here is an example of using the `rem` unit for the font size instead of pixels:
:::interactive_editor
```html
<link rel="stylesheet" href="styles.css" />
<p>This is regular text.</p>
<p class="para">This text is slightly larger.</p>
```
```css
.para {
font-size: 1.2rem;
@@ -71,6 +84,8 @@ Here is an example of using the `rem` unit for the font size instead of pixels:
}
```
:::
By setting the font size to `1.2rem`, the font size of the paragraph element will be 1.2 times the font size of the root element. If the user hasn't changed the default font size, the font size of the paragraph element will be `19.2px` because it is 1.2 times `16px`.
So when should you use `rem` units? `rem` units are preferred over pixels for typography because they scale proportionally with the user's browser settings. This makes your content more accessible to users with visual impairments.