feat(curriculum): add interactive examples to vh and vw lesson (#62953)

This commit is contained in:
Diem-Trang Pham
2025-10-22 18:31:17 -05:00
committed by GitHub
parent b99f643757
commit a70fb3a2e9

View File

@@ -5,7 +5,7 @@ challengeType: 19
dashedName: what-are-vh-and-vw-units
---
# --description--
# --interactive--
In CSS, `vh` and `vw` are viewport-relative units that allow you to size elements based on the dimensions of the browser window. These units are particularly useful for creating responsive designs that adapt to different screen sizes.
@@ -19,16 +19,56 @@ These units are especially handy when you want to create full-screen layouts or
For example, you might want to use them to create a hero section that always fills the entire screen:
:::interactive_editor
```html
<link rel="stylesheet" href="styles.css" />
<section class="hero">
<h1>100vh / 100vw Example</h1>
<p>This section fills the entire browser window.</p>
</section>
```
```css
body {
margin: 0;
font-family: sans-serif;
border: 5px dashed #333;
}
.hero {
height: 100vh;
width: 100vw;
background-color: #add8e6;
padding: 2em;
}
.hero h1 {
font-size: 2em;
margin-bottom: 0.5em;
}
.hero p {
font-size: 1em;
}
```
:::
This CSS ensures that the hero section will always be exactly the size of the viewport, regardless of the device's screen size.
`vh` and `vw` units can also be used for typography to create responsive text sizes. For instance:
`vh` and `vw` units can also be used for typography to create responsive text sizes.
Try adjusting the size of the preview window to see how the text scales with the viewport size:
:::interactive_editor
```html
<link rel="stylesheet" href="styles.css" />
<h1>Responsive Heading</h1>
<p>The h1 heading scales with the viewport width.</p>
```
```css
h1 {
@@ -36,6 +76,8 @@ h1 {
}
```
:::
This will set the font size of `h1` elements to 5% of the viewport width, allowing the text to scale smoothly with the browser window size.
One of the advantages of `vh` and `vw` units is that they respond to changes in the viewport size in real-time. This means that if a user resizes their browser window, elements sized with these units will adjust accordingly without needing to reload the page. However, it's important to use these units judiciously. Setting font sizes solely with `vw` units, for example, can lead to text becoming too small on narrow screens or too large on wide screens.