Skip to content

Commit 22d8236

Browse files
Merge pull request #227 from brechtDR/article/relative-length-units-based-on-the-viewport
[Article] Relative length units based on the viewport
2 parents 4eecf0e + b3762bd commit 22d8236

File tree

6 files changed

+259
-1
lines changed

6 files changed

+259
-1
lines changed

data/authors/brecht-de-ruyte.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
name: Brecht De Ruyte
33
avatar: /authors/brecht-de-ruyte.jpg
4-
occupation: Frontend Developer
4+
occupation: Frontend Developer / DevRel
55
twitter: https://twitter.com/utilitybend
66
linkedin: https://www.linkedin.com/in/utilitybend/
77
website: https://utilitybend.com/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,258 @@
1+
---
2+
title: 'Going beyond pixels and (r)ems in CSS - Relative length units based on the viewport'
3+
date: '2024-02-08'
4+
tags: ['frontend', 'css']
5+
images: ['/articles/going-beyond-pixels-and-rems-in-css/visual-pixel-viewport.jpg']
6+
summary: 'In this second part of the series, let’s talk about units based on the viewport also known as "the viewport-percentage length units". A lot of developers know these, but they can create some unexpected behavior, especially in combination with scrollbars and mobile behavior. Based on some articles and videos I picked up on the web from time to time, I''d like to explain some of the common pitfalls when using viewport units.'
7+
authors: ['brecht-de-ruyte']
8+
theme: 'beige'
9+
serie: 'going-beyond-pixels-and-rems-in-css'
10+
---
11+
12+
If you read the previous article in this series, you might’ve remembered that I’m using a [list on MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/length) as a template to create these articles, even if it’s just for the structure. But in contrast to the list on MDN, I will take a bit of a different approach with these particular units, as I want to focus a bit more on the most common pitfalls. Once again, I will start off with the theory and basics and then move on to examples or pitfalls. Now let’s get to it.
13+
14+
## vw
15+
16+
The `vw` unit stands for viewport width. But let’s start off with a catch right away. There are multiple things that we point at when talking about the viewport.
17+
18+
**The layout viewport** is the visible area of a web page influenced by the browser window or device screen size. It determines the space available for rendering HTML content. If you positioned a fixed box around the window, that’s the viewport we’re talking about.
19+
20+
```html
21+
<div class="viewport"></div>
22+
```
23+
24+
```css
25+
.viewport {
26+
position: fixed;
27+
inset: 0;
28+
outline: 10px dashed green;
29+
outline-offset: -10px;
30+
}
31+
```
32+
33+
**The initial containing block** is a conceptual box serving as the root of the CSS box model. Its dimensions are tied to the layout viewport, with the top-left corner at (0,0). As the ICB is our root element, we can show it like this:
34+
35+
```css
36+
html {
37+
width: 100%;
38+
height: 100%;
39+
outline: 10px solid hotpink;
40+
outline-offset: -10px;
41+
}
42+
```
43+
44+
To visualize this, look at this little pen, showing the layout viewport in green and the ICB in hotpink. When we scroll the page, we can see how they behave in correlation to each other:
45+
46+
<iframe
47+
height="300"
48+
class="simple-embed"
49+
scrolling="no"
50+
title="Layout viewport vs initial containing block"
51+
src="https://codepen.io/utilitybend/embed/preview/xxBYNox?default-tab=result&theme-id=dark"
52+
frameborder="no"
53+
loading="lazy"
54+
allowtransparency="true"
55+
allowfullscreen="true"
56+
>
57+
See the Pen{' '}
58+
<a href="https://codepen.io/utilitybend/pen/xxBYNox">
59+
Layout viewport vs initial containing block
60+
</a>
61+
&nbsp;by utilitybend (<a href="https://codepen.io/utilitybend">@utilitybend</a>) on <a href="https://codepen.io">
62+
CodePen
63+
</a>.
64+
</iframe>
65+
66+
By giving the ICB a height of 100% we notice that the ICB follows along while the user scrolls, but the viewport will remain in place.
67+
68+
### So why is this relevant to the vw unit?
69+
70+
Well, **according to spec:** The viewport-percentage lengths are relative to the size of the **initial containing block** - which is itself based on the size of either the viewport or the page area. When the height or width of the initial containing block is changed, they are scaled accordingly.
71+
72+
So yes, still in general, this relative length unit represents a percentage of the viewport width as the ICB is initially scaled on the viewport. For example, if the viewport width is 1000 pixels, then `1vw` is equal to 10 pixels (1% of 1000 pixels). Still, it’s nice to know this little nuance.
73+
74+
### 100vw and author frustration
75+
76+
This is a common frustration for people writing CSS. When we position something absolute and give it a width of `100vw`, we sometimes come in a situation where we have a horizontal scroll. This behavior is only visible when scroll bars are fixed and not with the overlay type of scrollbar. To enable this on macOS, go to `system settings > appearance > show scroll bars` and set this to `always`. The default is based on whether a mouse is connected or a trackpad is used.
77+
78+
**Hot tip:** I personally have this as a default, just so I can spot these kinds of issues while developing.
79+
80+
It is a common frustration and the easy way out is to use a width of `100%`, if that isn’t an option, there are methods to calculate the width of the scroll bar, and you could calculate `100vw` and subtract the scroll bar width (I have hacked my way around that before).
81+
82+
**The reason for this is in the spec:** In all cases, scrollbars are assumed not to exist. Note however that the initial containing block's size is affected by the presence of scrollbars on the viewport.
83+
84+
This is a basic example on where it can go wrong, be sure to toggle your scrollbar to show if you’re on macOS.
85+
86+
<iframe
87+
height="300"
88+
class="simple-embed"
89+
scrolling="no"
90+
title="100vw horizontal scroll example"
91+
src="https://codepen.io/utilitybend/embed/preview/YzgLPQL?default-tab=result&theme-id=dark"
92+
frameborder="no"
93+
loading="lazy"
94+
allowtransparency="true"
95+
allowfullscreen="true"
96+
>
97+
See the Pen{' '}
98+
<a href="https://codepen.io/utilitybend/pen/YzgLPQL">100vw horizontal scroll example</a> by
99+
utilitybend (<a href="https://codepen.io/utilitybend">@utilitybend</a>) on{' '}
100+
<a href="https://codepen.io">CodePen</a>.
101+
</iframe>
102+
103+
So what are `vw` units used for? Usually just sizing items, but they can be used as a `font-size` as well. Do notice that it can cause accessibility issues. One of the most interesting ways to use them for font-sizes is fluid typography when using the CSS `clamp()` function:
104+
105+
```css
106+
body {
107+
font-family: sans-serif;
108+
font-size: clamp(1rem, 0.8696rem + 0.6522vw, 1.375rem);
109+
line-height: 1.5;
110+
}
111+
```
112+
113+
<iframe
114+
height="300"
115+
class="simple-embed"
116+
scrolling="no"
117+
title="Simple clamp() example"
118+
src="https://codepen.io/utilitybend/embed/preview/bGZMbKq?default-tab=result&theme-id=dark"
119+
frameborder="no"
120+
loading="lazy"
121+
allowtransparency="true"
122+
allowfullscreen="true"
123+
>
124+
See the Pen <a href="https://codepen.io/utilitybend/pen/bGZMbKq">Simple clamp() example</a> by
125+
utilitybend (<a href="https://codepen.io/utilitybend">@utilitybend</a>) on{' '}
126+
<a href="https://codepen.io">CodePen</a>.
127+
</iframe>
128+
129+
In this example, I’m using `vw` as an example to create the slope, but it could be any of the units. A great starting point for fluid typography is [utopia.fyi](https://utopia.fyi/) (this uses the `vi` unit, but we’ll get there). In some cases (for example portrait ratios), even a `vh` unit could make a lot of sense for fluid typography. So let's jump to that.
130+
131+
## vh
132+
133+
Just as the `vw` unit is for width, the `vh` unit stands for viewport height. It is a relative unit that represents a percentage of the viewport's height. For example, if you set an element's height to `50vh`, it will be half of the viewport's height. As previously mentioned, this is actually the height of the ICB, which is the size of the viewport by default.
134+
135+
This behavior is all fine and dandy when we’re looking at our desktop browser, but from the moment we start using this unit on our mobile browser, “stuff happens” and it’s… not pretty.
136+
137+
When we scroll on a mobile browser after page load we often get a particular behavior: some items start to move or collapse, such as the address bar.
138+
139+
Let’s take it to the test. In our HTML, we add the following:
140+
141+
```html
142+
<div class="vh">
143+
<h2>This item is at the bottom of 100vh</h2>
144+
</div>
145+
```
146+
147+
And in our CSS we do the following:
148+
149+
```css
150+
.vh {
151+
display: flex;
152+
flex-direction: column;
153+
align-items: center;
154+
justify-content: flex-end;
155+
width: 100%;
156+
height: 100vh;
157+
background: skyblue;
158+
}
159+
160+
body {
161+
margin: 0;
162+
}
163+
```
164+
165+
This results to the following behavior:
166+
167+
**Desktop**
168+
169+
![100vh on desktop](/articles/going-beyond-pixels-and-rems-in-css/vh-desktop.png)
170+
171+
**Mobile Safari (iOS)**
172+
173+
<div class="mx-auto w-1/2">
174+
![100vh on mobile Safari](/articles/going-beyond-pixels-and-rems-in-css/vh-mobile.png)
175+
</div>
176+
177+
Notice, how our text is not aligned to the bottom on the mobile browser at page load. That’s because a `100vh` is `100%` of the viewport height when the address bar is collapsed. Which means it can result in unwanted behavior in some cases.
178+
179+
Luckily, there is a solution for this, but let’s get the other default units first:
180+
181+
## vb and vi: block and inline
182+
183+
`vi` and `vb`, the new kids on the block (pun intended!). They are the logical counterparts to `vw` and `vh` to handle multilingual layouts flawlessly. These units will take the writing mode into account, for us in the west, the inline axis is horizontal, and the block axis is vertical. As mentioned before, [utopia.fyi](https://utopia.fyi/) also uses these logical variants.
184+
185+
## vmin and vmax
186+
187+
The `vmin` unit represents the smallest between the viewport width and height, while `vmax` represents the largest between the viewport width and height. This can be especially handy when switching between portrait and landscape situations.
188+
189+
A quick visualization (play around with your window aspect ratio and size):
190+
191+
<iframe
192+
height="300"
193+
class="simple-embed"
194+
scrolling="no"
195+
title="Untitled"
196+
src="https://codepen.io/utilitybend/embed/preview/oNVdNLj?default-tab=result&theme-id=dark"
197+
frameborder="no"
198+
loading="lazy"
199+
allowtransparency="true"
200+
allowfullscreen="true"
201+
>
202+
See the Pen <a href="https://codepen.io/utilitybend/pen/oNVdNLj">Untitled</a> by utilitybend (
203+
<a href="https://codepen.io/utilitybend">@utilitybend</a>) on{' '}
204+
<a href="https://codepen.io">CodePen</a>.
205+
</iframe>
206+
207+
A really handy example for this could be gaps in a grid. For this, I will re-use the old ch unit demo from the [previous article](https://techhub.iodigital.com/articles/going-beyond-pixels-and-rems-in-css/relative-length-units-based-on-font), but now take a look at the gap property and once again play around with the window size and aspect ratio:
208+
209+
<iframe
210+
height="300"
211+
class="simple-embed"
212+
scrolling="no"
213+
title="Using ch unit for responsive behaviour"
214+
src="https://codepen.io/utilitybend/embed/preview/vYPWXMK?default-tab=result&theme-id=dark"
215+
frameborder="no"
216+
loading="lazy"
217+
allowtransparency="true"
218+
allowfullscreen="true"
219+
>
220+
See the Pen{' '}
221+
<a href="https://codepen.io/utilitybend/pen/vYPWXMK">Using ch unit for responsive behaviour</a> by
222+
utilitybend (<a href="https://codepen.io/utilitybend">@utilitybend</a>) on{' '}
223+
<a href="https://codepen.io">CodePen</a>.
224+
</iframe>
225+
226+
## Large, Small and Dynamic
227+
228+
Let’s talk about the ~~drug~~ heroes for all our mobile browser frustrations. These modifiers or prefixes can be added to all of the above units in the form of `l`, `s`, or `d`.
229+
230+
- `l` (large): Represents the viewport size, without any dynamic elements like address bars or toolbars that might be hidden or expanded.
231+
- `s` (small): Represents the viewport size with those dynamic elements factored in.
232+
- `d` (dynamic): Calculates the difference between the large and small viewports, offering a dynamic unit that adjusts as elements show or hide.
233+
234+
This is an example of `svh` and `lvh` when viewed in mobile Safari. When scrolling down, you can notice that `lvh` is the size of the window height plus the address bar height. The green outline is wrapped around the two elements for better visualization.
235+
236+
![100vh on mobile Safari](/articles/going-beyond-pixels-and-rems-in-css/lvh-svh-compare.jpg)
237+
238+
[Here is a codepen link if you want to try it out on your phone](https://cdpn.io/pen/debug/ExMLxqK)
239+
240+
## There is an excellent video
241+
242+
If you want to get a bit more into detail, there is an excellent video by [Bramus](https://bram.us) and [Jake](https://jakearchibald.com/) about this and probably one of my favorite web-related videos of all time, it’s probably where I learned about the term “ICB” in the first place. Although it was released before the dynamic units were supported everywhere, it is still full of information and great examples. Always respect the source material ;) enjoy:
243+
244+
<iframe
245+
width="560"
246+
height="315"
247+
class="simple-embed"
248+
src="https://www.youtube.com/embed/xl9R8aTOW_I?si=GH2CNV9juY-w6tiN"
249+
title="It's viewports all the way down | HTTP 203"
250+
frameborder="0"
251+
loading="lazy"
252+
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
253+
allowfullscreen
254+
></iframe>
255+
256+
If you’d rather take a deep dive in the complete spec of all the level 4 units, you can always [check out the spec](https://drafts.csswg.org/css-values-4/).
257+
258+
That’s it for part two! In part three we’re going a bit more modern with container units. Looking forward to creating some awesome demo’s with those.
Loading
Loading
Loading
Loading

0 commit comments

Comments
 (0)