Identify and Extract Pseudo-Element Selectors from built-in HTML Elements using DevTools

Recently Stefan Judis shared how to style the browse button of a file selector using the ::file-selector-button pseudo-element

But what about other complex elements in the browser? How can we tweak individual parts of those? Take <audio> for example: is there a pseudo-element we can use to style the play button?

~

Table of Contents

  1. Dissecting <input type="file" />
  2. How to use DevTools to peek inside <input type="file" />
  3. Dissecting <audio>
  4. Is there a catch?
  5. One last thing

~

# Dissecting <input type="file" />

Before we answer the question above, let’s first take a look at the <input type="file" /> Stefan used. Below is screenshot of how it’s rendered in Chromium on Mac, with a few extra outlines added.

Even though we only type 1 element in our HTML code, we see it consists of two parts:

  1. A “Choose File” button
  2. A label reading “No file chosen”

Internally, this is also how the browser builds it. We type in:

<input type="file" />

But what’s being rendered is this:

<input type="button" value="Choose file" pseudo="-webkit-file-upload-button" id="file-upload-button">
<span aria-hidden="true">No file chosen</span>

(I’ll show you further down this post how I know this 😉)

The ::file-selector-button selector Stefan mentioned targets only the <input type="button" …> you see there. Using it you can style the button, like he did.

🧐 If you’re paying close attention you might notice that the pseudo-element used is ::file-selector-button, whilst the pseudo attribute of the button reads -webkit-file-upload-button. More on that further down the post 😉

~

# How to use DevTools to peek inside <input type="file" />

In the Chromium DevTools we don’t get to see the two elements that make up <input type="file" />. That’s because this information as is hidden in the Shadow DOM.

Thankfully there is a way to have DevTools show them. To do so, open DevTools’ Settings, and under Elements check the option that reads “Show user agent Shadow DOM”.

🦊 Firefox or 🧭 Safari user? The DevTools in Firefox/Safari have this option enabled out of the box.

Once enabled you’ll see #shadow-root (user-agent) appear in the Elements Tree for all elements that are built that way (and there quite a few!).

<input type="file">
  ↳ #shadow-root (user-agent)
      <input type="button" value="Choose file" pseudo="-webkit-file-upload-button" id="file-upload-button">
      <span aria-hidden="true">No file chosen</span>
</input>

☝️ Having this option enabled all the time can be quite distracting. I personally only turn it on when I need it.

~

# Dissecting <audio>

Winging back to our initial question “is there a pseudo-element we can use to style the play button?”, we can use the DevTools to see the underlying structure.

In Chromium we get back this structure:

<audio controls="" src="/media/cc0-audio/t-rex-roar.mp3">
  ↳ #shadow-root (user-agent)
    <div pseudo="-webkit-media-controls" class="phase-ready state-stopped">
      <div pseudo="-webkit-media-controls-overlay-enclosure">
        <input pseudo="-internal-media-controls-overlay-cast-button" type="button" aria-label="play on remote device" style="display: none;">
      </div>
      <div pseudo="-webkit-media-controls-enclosure">
        <div pseudo="-webkit-media-controls-panel">
          <input type="button" pseudo="-webkit-media-controls-play-button" aria-label="play" class="pause" style="">
          <div aria-label="elapsed time: 0:00" pseudo="-webkit-media-controls-current-time-display" style="">0:00</div>
          <div aria-label="total time: / 0:02" pseudo="-webkit-media-controls-time-remaining-display" style="">/ 0:02</div>
          <input type="range" step="any" pseudo="-webkit-media-controls-timeline" max="2.115918" aria-label="audio time scrubber 0:00 / 0:02" aria-valuetext="elapsed time: 0:00">
          <div pseudo="-webkit-media-controls-volume-control-container" class="closed" style="">
            <div pseudo="-webkit-media-controls-volume-control-hover-background"></div>
            <input type="range" step="any" max="1" aria-valuemax="100" aria-valuemin="0" aria-label="volume" pseudo="-webkit-media-controls-volume-slider" aria-valuenow="100" class="closed" style=""><input type="button" pseudo="-webkit-media-controls-mute-button" aria-label="mute" style="">
          </div>
          <input type="button" pseudo="-webkit-media-controls-fullscreen-button" aria-label="enter full screen" style="display: none;">
          <input type="button" aria-label="show more media controls" title="more options" pseudo="-internal-media-controls-overflow-button" style="">
        </div>
      </div>
      <div role="menu" aria-label="Options" pseudo="-internal-media-controls-text-track-list" style="display: none;"></div>
      <div pseudo="-internal-media-controls-overflow-menu-list" role="menu" class="closed" style="display: none;">
        <label pseudo="-internal-media-controls-overflow-menu-list-item" role="menuitem" tabindex="0" aria-label=" Play " style="display: none;">
          <input type="button" pseudo="-webkit-media-controls-play-button" tabindex="-1" aria-label="play" class="pause" style="display: none;">
          <div aria-hidden="true">
            <span>Play</span>
          </div>
        </label>
        <label pseudo="-internal-media-controls-overflow-menu-list-item" role="menuitem" tabindex="0" aria-label="enter full screen Full screen " style="display: none;">
          <input type="button" pseudo="-webkit-media-controls-fullscreen-button" aria-label="enter full screen" tabindex="-1" style="display: none;">
          <div aria-hidden="true">
            <span>Full screen</span>
          </div>
        </label>
        <label pseudo="-internal-media-controls-overflow-menu-list-item" role="menuitem" tabindex="0" aria-label="download media Download " class="animated-0" style="">
          <input type="button" aria-label="download media" pseudo="-internal-media-controls-download-button" tabindex="-1" style="">
          <div aria-hidden="true">
            <span>Download</span>
          </div>
        </label>
        <label pseudo="-internal-media-controls-overflow-menu-list-item" role="menuitem" tabindex="0" aria-label=" Mute " class="animated-2" style="display: none;">
          <input type="button" pseudo="-webkit-media-controls-mute-button" tabindex="-1" aria-label="mute" style="display: none;">
          <div aria-hidden="true">
            <span>Mute</span>
          </div>
        </label>
        <label pseudo="-internal-media-controls-overflow-menu-list-item" role="menuitem" tabindex="0" aria-label="play on remote device Cast " class="animated-1" style="display: none;">
          <input pseudo="-internal-media-controls-cast-button" type="button" aria-label="play on remote device" tabindex="-1" style="display: none;">
          <div aria-hidden="true">
            <span>Cast</span>
          </div>
        </label>
        <label pseudo="-internal-media-controls-overflow-menu-list-item" role="menuitem" tabindex="0" aria-label="show closed captions menu Captions " class="animated-0" style="display: none;">
          <input aria-label="show closed captions menu" type="button" pseudo="-webkit-media-controls-toggle-closed-captions-button" tabindex="-1" style="display: none;">
          <div aria-hidden="true">
            <span>Captions</span>
          </div>
        </label>
      </div>
    </div>
</audio>

Or visually, with outlines added:

With a bit of digging we can find the the play button on line #9, and extract its pseudo attribute.

<input type="button" pseudo="-webkit-media-controls-play-button" aria-label="play" class="pause" style="">

👉 To style the play button we can use ::-webkit-media-controls-play-button

~

# Is there a catch?

While the ::-webkit-media-controls-play-button selector above works, there’s a catch though: it only works in Chromium based browsers, and this for several reasons:

  1. Every browser engine has its own implementation for what makes up an <audio> element. Shown below is a comparison of the UI for the <audio> as seen in Firefox, Chromium, and Safari.

    Whilst all implementation contain a play button, not all — for example — contain an element that indicates the current time. Styling that wouldn’t be possible.

  2. Not all browser expose the same parts of the UI using pseudo-elements. When it comes to <audio> for example, only Chromium exposes parts of its UI. Firefox and Safari don’t expose any pseudo-element for <audio>

    And even if they would, the wouldn’t use ::-webkit-media-controls-play-button for it.

Another aspect to take into account is that ::-webkit-media-controls-play-button is something that Chromium decided to use. This wasn’t discussed with any other browser vendor. As Thomas Steiner warns:

~

# One last thing

To close off I still owe you an explanation to why Chromium lists ::-webkit-file-upload-button for the browse button of <input type="file" />, instead of ::file-selector-button.

This is because they first exposed it using their own internal ::-webkit-file-upload-button name. It was only later that the CSS Working Group decided to standardize it to ::file-selector-button.

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

Scroll-Linked Animations with CSS Scroll-Timeline (CSS Conf Colombia)

I just finished giving a lightning talk at the wonderful CSS Conf Colombia covering Scroll-Linked Animations with CSS @scroll-timeline. Really enjoyed giving a talk again after all this time, especially with this great vibe they have going on and the afterparty in gather.town (skribbl FTW!).

You can find the slides embedded below:

Source materials for the slides are my two posts on Scroll-Linked Animations:

  1. Part 1: Intro + Basic Scroll-Linked Animations
  2. Part 2: Scroll-Linked Animations with Element-Based Offsets

I’ll try to see if I can get a hold of the recording to embed here.

Thanks to the organisers for having me, and thanks to the attendees for watching me speak. I hope you all had fun attending this talk. I know I had making it (and whilst bringing it forward) 🙂

💁‍♂️ If you are a conference or meetup organiser, don’t hesitate to contact me to come speak at your event.

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

CSS Container Queries: A First Look + Demo

Back in November 2020 it was announced that Chromium would experiment with Container Queries — back then just a proposal but earlier this year (February 2021) adopted to become part of the CSS Containment Module Level 3 Specification.

Just before the weekend a first version of this experimental implementation landed in Chromium Canary for us to play with (behind a flag). Let’s take it for a test drive …

👨‍🔬 The CSS features described in this post are still experimental and not finalized at all! If you’re feeling adventurous you can play with these new features today, but you’ll need at least Chromium 91.0.4459.0 with the #enable-container-queries flag enabled through chrome://flags.

~

Wanting to test Container Queries out I quickly threw a demo together using a classic card component. By default our component shows and image on top and a description below that. If enough space becomes available, they will be shown next to each other. Should even more space become available, then the image will grow even more.

In the recording below you can see the different layouts we want to achieve:

~

The markup for all those cards is the same and is pretty straightforward. Only extra thing I’ve added is an extra wrapper div .animalcard-wrapper so that our container queries will play nice when being used inside CSS Grid

<div class="animalcard-wrapper">
	<div class="animalcard">
		<div class="animalcard__image">
			…
		</div>
		<div class="animalcard__description">
			…
		</div>
	</div>
</div>

The default layout of our card uses CSS Grid to position the image and the description:

/* SMALL LAYOUT: Image stacked on top of Description */
.animalcard {
	display: grid;
	grid-template: "image" "description" / 1fr;
	gap: 1em;
	padding: 1em;
}

To be able to use Container Queries, we first need to create a Containment Context (Container Root) on the .animalcard-wrapper. We instruct the browser to keep track of the inline-size, which translates to the width, as we will be changing the layout of its children based on that dimension.

/* Container Queries: Create Container Root */
.animalcard-wrapper {
	contain: layout inline-size;
}

With this Container Root in place, we can now add extra styles to apply when the Container Root reaches a certain width

/* MEDIUM LAYOUT: Image next to Description (1fr each) */
@container (min-width: 30rem) {
	.animalcard {
		gap: 2em;
		padding: 2em;
		grid-template: "image description" / 1fr 1fr;
	}

	.animalcard__description {
		text-align: left;
	}
}

/* LARGE LAYOUT: Large Image next to Description */
@container (min-width: 70rem) {
	.animalcard {
		grid-template-columns: 2fr 1fr;
	}
}

~

All together our demo finally becomes this:

See the Pen CSS Container Queries Demo by Bramus (@bramus) on CodePen.

😊

☝️ If you’re looking for more demos, Miriam Suzanne is collecting a bunch in this CodePen Collection. Be sure to check out Una‘s Episode Card for The CSS Podcast

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

Three important things you should know about CSS :is()

Back in 2019 I shared how the CSS :is() selector will simplify things when writing CSS. What I didn’t know back then, and only have learnt quite recently, are these three important facts about CSS :is():

  1. The selector list of :is() is forgiving
  2. The specificity of :is() is that of its most specific argument
  3. :is() does not work with pseudo-element selectors (for now)

Let’s take look at what that means.

~

# 1. The selector list of :is() is forgiving

What if you include a selector that’s pure gibberish inside :is()? Will the rule-set be declared invalid or what?

p:is(.foo, #bar, $css:rocks) {
  color: hotpink;
}

Thankfully :is() is very forgiving here: the $css:rocks part — which in itself is an invalid CSS selector — will simply be ignored, while keeping the rest of the selector list in place.. So using the snippet above, both p.foo and p#bar will be colored hotpink. Yay!

Should you try this without :is(), the whole rule-set would become invalid. In the snippet below, none of the paragraphs will be hotpink due to that faulty $css:rocks selector invalidating the whole selector list.

p {
  font-family: sans-serif;
}

p.foo, p#bar, p$css:rocks { /* ❌ This whole rule-set is declared invalid */
  color: hotpink;
}

Note that the paragraphs will have font-family: sans-serif applied, as it’s only the invalid rule-set that ends up being ignored.

🔮 In the near future this latter behavior will no longer be the case as the CSSWG intends to modify these rules such that an invalid selector will simply be ignored rather than invalidating the whole selector list. Relevant CSS WG Issue: 3264

~

# 2. The specificity of :is() is that of its most specific argument

Take the code below. What color will p.foo have?

p:is(.foo, #bar, $this:invalid) {
  color: hotpink;
}

p.foo {
  color: lime;
}

I won’t be lime but hotpink! This because when calculating the specificity, the specificity of the :is() pseudo-class is replaced by the specificity of its most specific argument.

  • p.foo has a specificity of (0,1,1)
  • p:is(.foo, #bar) has a specificity of (1,0,1)

As p:is(.foo, #bar) has a higher specificity, it will “win” here.

☝️ The :not() and :has() pseudo-classes also have their specificity calculated this way.

☝️ If you don’t want to be affected by this, you can use :where() instead of :is(). It works in the same way :is() does, but will always have a specificity of 0. You can cleverly wrap this around other selectors to undo their specificity. Think of :where(:not(…)) for example.

😬 Although I wouldn’t recommend it, you could perfectly do something like :is(#bump#up#the#spe#ci#fi#city#yo, .foo) to override selectors more specific than .foo

~

# 3. :is() does not work with pseudo-element selectors (for now)

If you read up on the definition of :is() you’ll read that it accepts a “Selector List” which is a comma-separated list of simple, compound, or complex selectors.

When looking up simple selectors, there’s an interesting thing to note:

A type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class is a simple selector.

Do you see it? Here: pseudo-element selectors are not included in this list. As a result, :is() does not play nice with pseudo-element selectors such as ::before, ::after, ….

🔮 In the future this will become possible though, but not just yet. Relevant CSSWG Issue: 2284

~

Knowing these three facts about :is() will surely help you understand it better and make using it more fun!

See the Pen The CSS :is() pseudo-class. What color will .foo have? by Bramus (@bramus) on CodePen.

If you understood well, the Pen above should hold no secrets to you anymore 🙂

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

The Future of CSS: Scroll-Linked Animations with @scroll-timeline (Part 2)

Example Scroll-Linked Animation with Element-Based Offsets, CSS FTW! 🤩

The Scroll-linked Animations Specification is an upcoming addition to CSS that defines a way for creating animations that are linked to a scroll offset of a scroll container. Even though the specification is still in draft, and in no way finalized nor official, it already has experimental support in Chromium.

In the first part of this series we covered how to create Scroll-Linked Animations between two absolute scroll-offsets using the @scroll-timeline at-rule and animation-timeline CSS property.

In this second part we dial it up a notch and dig into creating Scroll-Linked Animations based on the location of an element within its scroller.

~

👨‍🔬 The CSS features described in this post are still experimental and not finalized at all! If you’re feeling adventurous you can play with these new features today, but you’ll need at least Chromium 89 with the #experimental-web-platform-features flag enabled through chrome://flags.

💥 To keep your primary Chrome install clean, I recommend you do not set this in Chrome Stable, but resort to Beta / Canary builds.

👀 If you don’t understand how to do this, or don’t feel safe doing this, fear not: This post also includes recordings and/or fallback versions using JavaScript for most of the demos.

💄 While the Scroll-Linked Animations Specification also describes a JavaScript interface, the main focus of this post will be its CSS counterpart. The JS alternatives won’t be covered in detail.

~

Table of Contents

  1. Scroll-Linked Animations (Part 1), a Recap
  2. Element-based Offsets?
  3. Element-based Offsets in CSS
  4. Element-based Offsets and @scroll-timeline (Revealing Image Demo)
  5. Typical from/to <element-offset> Combinations
  6. Demos
    1. Revealing Images Demo, Revisited
    2. Contact List Demo
    3. Contact List Demo, Revisited
    4. Horizontal Scroll Section Demo
    5. CoverFlow Demo
    6. Stacking Cards Demo
  7. In Closing

~

# Scroll-Linked Animations (Part 1), a Recap

In the first part of this series we took a look at @scroll-timeline and its descriptors. If I explained it all properly, the code snippet below should make sense:

@keyframes resize-progressbar {
  to {
    transform: scaleX(1);
  }
}

@scroll-timeline scroll-in-gallery {
  source: selector(#gallery__scrollcontainer);
  scroll-offsets: 0%, 100%;
  orientation: horizontal;
  time-range: 1s;
}

#gallery__progressbar {
  transform: scaleX(0.5);
  animation: 1s linear forwards resize-progressbar;
  animation-timeline: scroll-in-gallery;
}

🚨 It’s very important to understand the contents of the first part of this series as this post builds further upon that knowledge. If you haven’t read it, you most likely won’t understand all that much of this second part. You can read the first part here.

~

# Element-based Offsets?

Besides setting absolute values as scroll-offsets, the Scroll-Linked Animations Specification also allows you to set Element-based Scroll Offsets. With this type of Scroll Offsets the animation is based on the location of an element within the scroll-container.

Typically this is used to animate an element as it comes into the scrollport until it has left the scrollport; e.g. while it is intersecting:

See the Pen Scroll-Linked Animations Visualization: Element-Based Offsets by Bramus (@bramus) on CodePen.

When scrolling down in the visualization (using the ⏭ button) you’ll see the box switch colors:

  1. as it slides into the scrollport from the bottom
  2. after it has just left the scrollport at the top

🔄 When scrolling back up again you’ll see the same happening in reverse.

Both these turning points can be used as offsets for a Scroll-Linked Animations. Because they are described from the perspective of the box itself (which is an HTML Element), we call these “Element-based Offsets”.

In pseudo-code, our @scroll-timeline would look like this:

@scroll-timeline element-enters-and-leaves-the-scrollport {
  scroll-offsets:
    “the box is positioned underneath the bottom edge of the scrollport”,
    “the box is positioned above the top edge of the scrollport”
  ;
  time-range: 1s;
}

As with “regular” Scroll-Linked Animations we can drive an animation while scrolling between these two Element-based Offsets.

☝️ In an earlier version of the spec one had to define the Scroll Offsets using start and end descriptors.

@scroll-timeline element-enters-and-leaves-the-scrollport {
    start: “the box is positioned underneath the bottom edge of the scrollport”;
    end: “the box is positioned above the top edge of the scrollport”;
    time-range: 1s;
}

This is no longer the case, and one should now use the scroll-offsets descriptor instead.

However, you might still see this older syntax in the demos as Chromium has this older version implemented and is in the process of migrating to the new scroll-offsets syntax — Relevant Chromium Bug: 1094014

~

# Element-based Offsets in CSS

To create a Scroll-Linked Animation that uses Element-based Offsets, we first need two Element-based Offsets:

  1. A from offset which defines when the animation will begin.
  2. A to offset which defines by when the animation will be done.

In CSS, these Element-based Offsets are represented by the <element-offset> Data Type.

~

# The <element-offset> Data Type

Let’s take the example below and dissect it:

selector(#element) end 0
  1. selector(#element) defines the DOM Element we want keep an eye on. We call this the target.

  2. end indicates at which edge of the source‘s scrollport the algorithm should look for the target intersecting.

    • Allowed values are start/end.
    • Depending on the timeline’s orientation this translates to the top/bottom or left/right edge.
  3. The threshold is a number — ranging from 0.0 to 1.0 — that indicates how much of the target is visible in the scrollport at the given edge.

    • 0 = not in the scrollport
    • 1 = entirely in the scrollport

    You might already know this value from creating an IntersectionObserver.

Looking back at our example of selector(#element) end 0, it basically translates to:

  1. Keep an eye on #element
  2. … and track if it intersects at the end edge of source.
  3. If the element’s intersecting threshold is 0 then activate.

E.g. the #element is touching the scrollport at its bottom edge; which happens to be the starting point from the visualization before!

~

# Making it visual

If you cannot follow with that threshold there, don’t worry: it’s easier to understand if you make it visual.

See the Pen Scroll-Linked Animations Visualization: Element-Based Offsets Visualizer by Bramus (@bramus) on CodePen.

In the visualization above try changing the values, keeping in mind that the threshold is a number that indicates how much of the target is intersecting with the scrollport at the given edge.

If, after playing with it, you understand that a edge+threshold combo of start 0.5 means that the target is halfway across the top edge of a vertical scrollport, you get it 😎

🐛 I’ve noticed that it’s also possible to — for example — define end 1.2, which translates to “the target is 1/5th over the bottom edge”. This is not allowed per spec, as the threshold should be in the range of 0.0 and 1.0.

However, as the algorithm never checks whether this value is inside its assigned range, it passes through and will work. I kinda like this quirk, as it allows you to add some breathing room to all of your animations.

Could be in the future that this will no longer be allowed — Relevant CSS WG Issue: 5203

~

# Element-based Offsets and @scroll-timeline (Revealing Image Demo)

To create a Scroll-Linked Animation that uses Element-based Offsets, you need to pass a pair of <element-offset> Data Types into the @scroll-timeline‘s scroll-offsets descriptor.

@scroll-timeline element-enters-and-leaves-the-scrollport {
  scroll-offsets:
    selector(#element) end 0,
    selector(#element) start 0
  ;
  time-range: 1s;
}
  1. selector(#element) end 0 here is our from offset, and defines when the animation will begin.
  2. selector(#element) start 0 here is our to offset, and defines by when the animation will be done.

Here the offsets for our @scroll-timeline are set so that the animation will begin when #element is about to enter the scrollport from the bottom (= end edge, 0% in view), and will be done animating after the #element has entirely left the scrollport at the top (= start edge, 0% in view).

In this demo you’ll see an image be revealed as it intersects with the scrollport. The reveal itself is done using a clip-path that animates from inset(0% 50% 0% 50%); to no clipping at all, which looks like a curtain opening.

@keyframes reveal {
    to {
        clip-path: inset(0% 0% 0% 0%);
    }
}
.revealing-image {
    clip-path: inset(0% 50% 0% 50%);
    animation: reveal 2s linear;
    animation-fill-mode: forwards;
}

@scroll-timeline revealing-image-timeline {
    source: selector(body);
    scroll-offsets:
      selector(#revealing-image) end 0,
      selector(#revealing-image) start 0
    ;
    time-range: 2s;
}
#revealing-image {
    animation-timeline: revealing-image-timeline;
}

🤕 In this demo we have a loss of (visual) data though. As our animation reaches 100% only when the image has already slid out of scrollport (at the top), we can never see the image as a whole — it’s always clipped while inside the scrollport. Thankfully we can tweak the used <element-offset>s to prevent this loss of visual data.

~

# Typical from/to <element-offset> Combinations

There are 4 typical edge + threshold combinations to use with Scroll-Linked Animations:

  • start 0
  • start 1
  • end 1
  • end 0

☝️ As a reminder, here’s what they look like, individually:

See the Pen Scroll-Linked Animations Visualization: Element-Based Offsets Visualizer by Bramus (@bramus) on CodePen.

Other values for threshold of course still possible; I’m only taking a look at these extremes here.

Depending on how you combine these as to/from offsets, we can control when exactly the animation will run:

  • #element is intersecting scrollport, even for the tiniest bit
  • #element is in between scrollport edges
  • #element is entering from bottom into scrollport
  • #element is exiting at top from scrollport

In the demo below I’ve created several boxes that each have a different pair of <element-offset>s applied. Scroll down to see the elements appear in the viewport and take a good look at each box separately, specifically when one of its edges enters or leaves the viewport.

Color codes are applied to indicate when the element is being animated:

  • Red = the Scroll Timeline is not animating the element
  • Green = the Scroll Timeline is animating the element

Unfortunately there’s an issue with the used ScrollTimeline polyfill used, and the timelines are calculated wrongly. Showing this (broken) demo would only confuse you more, so it’s not included. Please to see how it behaves.

Did you see? Hit the checkbox at the top to have the demo show the findings. Perhaps you’ll see it now 😉

Interpreting the results from the demo, I’ve forged this small list of typical from-to offset combinations and what they look like:

  • end 0start 0 = intersecting scrollport, even for the tiniest bit
  • end 1start 1 = in between scrollport edges
  • end 0end 1 = enter from bottom into scrollport
  • start 1start 0 = exit at top from scrollport

In this extra visualization below you can see how these different combinations affect the timeline (drawn in the center). The same colors as in the demo are used.

See the Pen Scroll-Linked Animations Visualization: Element-Based Offsets Timeline Visualizer by Bramus (@bramus) on CodePen.

🥵 Don’t sweat it if you don’t understand this all immediately; it also took me quite some time before I did. And perhaps there’s no need to, as you can go a long way with this little cheat sheet:

  • end 0start 0 = intersecting scrollport, even for the tiniest bit
  • end 1start 1 = in between scrollport edges
  • end 0end 1 = enter from bottom into scrollport
  • start 1start 0 = exit at top from scrollport

~

# Demos

As I have been playing with CSS @scroll-timeline for nearly a month by now, I’ve whipped up quite a lot of extra demos. Ready to have your socks blown off? Here goes:

  1. Revealing Images Demo, Revisited
  2. Contact List Demo
  3. Contact List Demo, Revisited
  4. Horizontal Scroll Section Demo
  5. CoverFlow Demo
  6. Stacking Cards Demo

☝️ Know that all these demos here are technical demos. On a real website you might want to go easy with these types of animations in case visitors request so, by respecting their prefers-reduced-motion setting.

~

# Revealing Images Demo, Revisited

This demo is similar to the first Revealing Image one, yet the offsets were tweaked in such a way that the revealing animation should only start when the image is already halfway in view (read: threshold of 0.5) and be finished by the time the image has entered the scrollport completely.

In @scroll-timeline speak that becomes:

@scroll-timeline revealing-image-timeline-1 {
  source: selector(body);
  scroll-offsets:
    selector(#revealing-image-1) end 0.5,
    selector(#revealing-image-1) end 1
  ;
  time-range: 2s;
}

Above that the start clip-path was set to inset(45% 20% 45% 20%); — making it look like a revealing box — and the opacity is also animated.


.revealing-image {
  opacity: 0;
  clip-path: inset(45% 20% 45% 20%);
  …
}

~

# Contact List Demo

In this demo I’ve created a contact list where new items slide in when they enter the scrollport. I think it makes a neat effect 🙂

The list itself is a regular <ul> which acts as the @scroll-timeline‘s source. Each <li> has it’s own scroll-offset set to go from end 0 (= bottom edge, out of view) to end 1 (= bottom edge, in view).

@keyframes slide-in {
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

li {
  opacity: 0;
  transform: translateX(-100%);
  animation: 1s slide-in ease-in forwards;
}

@scroll-timeline list-item-15 {
  source: selector(#list-view);
  scroll-offsets:
    selector(#list-item-15) end 0,
    selector(#list-item-15) end 1
  ;
  time-range: 1s;
}
#list-item-15 {
  animation-timeline: list-item-15;
}
😳 ICYWW: No, I didn’t manually type out all those scroll-timelines

As also mentioned in the first part of this series it’s pretty annoying when it comes to creating scroll-timelines for many individual items as the selector() function requires you to pass an id into it. This is a shortcoming of the spec, and is something what will be tackled. Relevant CSS WG Issue: 5884

Until this issue is resolved — and to save myself from typing all those scroll-timelines out manually — I use a little piece of JavaScript to generate the timelines. These generated timelines can then be either copy-pasted into the CSS, or dynamically injected from the script.

const generateCSS = () => {
  const css = [];
  document.querySelectorAll('li').forEach((li, i) => {
    const id = li.getAttribute('id');

    css.push(`
      @scroll-timeline list-item-${id} {
        source: selector(#list-view);
        scroll-offsets:
          selector(#${id}) end 0,
          selector(#${id}) end 1
        ;
        time-range: 1s;
      }
      #${id} {
        animation-timeline: list-item-${id};
      }   

    `);
  });
  return css.join("\n");
}

const injectCSS = (css) => {
  const style = document.createElement('style');
  style.innerHTML = css;
  document.head.appendChild(style);
}

injectCSS(generateCSS());

In some demos you might notice that the generateCSS() code is still present, but not called. And even if it were: those demos still are pure CSS 😉

The animation on the <li>s in this demo was carefully chosen to be a horizontal one, so that the dimensions of the of the wrapping <ul>‘s scrollport don’t change. If the <li> elements would be translated in a vertical direction, that would also adjust the scrollport. You can work around this by animating not the <li> itself, but by animating its contents.

🔥 TIP: Beware with animations that alter the dimensions of the source‘s scrollbox. Work around it by not animating the target, but by animating the target’s contents.

💡 By flipping the animation and adjusting the scroll-offsets so that they are triggered at the start edge, you can easily create a version where items slide-out as they scroll out of the scrollport.

@keyframes slide-out {
  to {
    opacity: 0;
    transform: translateX(100%);
  }
}

li {
  opacity: 1;
  transform: translateX(0);
  animation: 1s slide-out ease-in forwards;
}

@scroll-timeline list-item-1 {
  source: selector(#list-view);
  scroll-offsets:
    selector(#list-item-1) start 1,
    selector(#list-item-1) start 0
  ;
  time-range: 1s;
}
#list-item-1 {
  animation-timeline: list-item-1;
}

~

# Contact List Demo, Revisited

Combining both the fly-in and fly-out effect is possible by creating 2 animations, each with their own individual (non-overlapping) @scroll-timeline

/* Element scrolls into the scroll-container (from the bottom) */
@scroll-timeline tl-list-item-12-appear {
  source: selector(#list-view);
  scroll-offsets:
    selector(#list-item-12) end 0,
    selector(#list-item-12) end 1
  ;
  time-range: 1s;
}

/* Element scrolls out of the scroll-container (at the top) */
@scroll-timeline tl-list-item-12-disappear {
  source: selector(#list-view);
  scroll-offsets:
    selector(#list-item-12) start 1,
    selector(#list-item-12) start 0
  ;
  time-range: 1s;
}

#list-item-12 > * {
  animation:
    1s li-appear linear tl-list-item-12-appear,
    1s li-disappear linear tl-list-item-12-disappear
  ;
}

Unfortunately there’s an issue with the used ScrollTimeline polyfill used, disallowing the combination of two animations. Please to see how this demo behaves.

What’s very crucial here — apart from having non-overlapping Scroll Timelines — is the attaching of the animations. Whereas in the previous demos it had animation-fill-mode: both; set, this has now been removed. This is a very important thing to do. If you don’t you’ll notice that only the last animation will be applied and might think this is an implementation bug as I did. Thankfully it’s not a bug and was a classic case of PEBKAC.

~

# Horizontal Scroll Section Demo

This demo is based upon this “GSAP ScrollTrigger & Locomotive Scroll” demo by Cameron Knight, which features a horizontal scroll section. I’ve basically left the HTML intact, removed all JS, and added a few CSS Animations + Scroll Timelines to get this working.

The tricky part was the horizontal section of course:

  1. Stretch out the wrapping #sectionPin to 500vh so that we create extra room to scroll.
  2. Set up a @scroll-timeline for #sectionPin while it’s inside entirely covering the scrollport, using the mind-flipping start 1end 1 offset combination.

    @scroll-timeline horizontal-section-scrolling-into-view {
      source: selector(body);
      scroll-offsets:
        selector(#sectionPin) start 1, /* Start when #sectionPin touches the top edge of the scrollport and is visible inside the scrollport */
        selector(#sectionPin) end 1 /* End when #sectionPin touches the bottom edge of the scrollport and is visible inside the scrollport */
      :
      time-range: 1s;
    }

    This weird offset combination only works because #sectionPin is bigger than the scrollport. I’ll leave it to you, the reader, to dig into it further 😉

  3. On .pin-wrap use position: sticky; (so that it remains in view) and translate it horizontally while scrolling.

    @keyframes move-horizontal-scrolling-section {
      to {
        transform: translateX(calc(-100% + 100vw)); /* Move horizontally so that right edge is aligned against the viewport */
      }
    }
      
    .pin-wrap {
      position: sticky;
      top: 0;
    
      animation: 1s linear move-horizontal-scrolling-section forwards;
      animation-timeline: horizontal-section-scrolling-into-view;
    }
☝️ What’s remarkable here is that the @scroll-timeline is tracking #sectionPin, but the animation is applied to it’s child element .pin-wrap. This is truly one of the powers of @scroll-timeline.
🐛 Want to dig deeper? Here’s a rendering glitch you might notice:

Upon reversing the animation when scrolling back up, it glitches.

This is a confirmed bug which will hopefully be fixed soon. — Relevant Chromium Bug: 1175289

~

# CoverFlow Demo

Remember CoverFlow from iTunes? Well, here’s a CSS-only version built with @scroll-timeline! 🎉

Looking under hood, here’s how it’s structured:

  1. The <ul> element is the scroll container, and the <li> elements inside scroll.
  2. The <li> elements themselves switch z-index, and their contained <img /> elements are transformed.

That 2nd thing is quite key here: If we were to transform the <li> elements the scroll-container’s width would change. This would make the scroll-linked animation recalculate at every change, resulting in a flickering animation. We don’t want that of course.

💿 Album covers in this demo come from the wonderful Loci Records label. You should definitely check them out. Their “Season Two” compilation is a good start: https://locirecords.com/season-two/

🐛 In this demo you’ll notice the native ScrollTimeline implementation in Chromium being buggy. Click for more details/info.

If you have “Experimental Web Platform Features” enabled you’ll notice two bugs in this demo:

  1. The z-index is not always applied correctly (slight flicker).
  2. (Not shown in video above) Elements at the very start over very end animate “too late”/”too soon”

You can see this second issue in the recording below:

On load card_0 and its siblings start at 0% animation progress, no matter what their position inside the scroll-container. When scrolling horizontally you see the first few items “catch up” with their animation state. By hitting card_5 the animation renders as expected: the item shown in the middle is at animation progress 50%. You can this very same wrong behavior again when closing in on the right edge: the last 5 items have the same issue (but in reverse). By the time the last card is in the center, its animation progress is 100%, whereas it should be at 50%.

This debug session shows best:

For reference, in a non-buggy implementation the initial rendering would show card_0 at 50% animation progress, as it’s positioned halfway the scrollport:

Relevant Chromium Bug: 1174838

~

# Stacking Cards Demo

In this demo I tried recreating this Stacking Cards demo from CodyHouse, initially by Claudia Romano.

See the Pen 🌟 Stacking Cards, Final Version by Bramus (@bramus) on CodePen.

Thanks to playing with animation-delay I’m able to use one shared @scroll-timeline for each card

:root {
  --numcards: 4;
}

#card_1 { --index: 1; }
#card_2 { --index: 2; }
#card_3 { --index: 3; }
#card_4 { --index: 4; }

@scroll-timeline cards-element-scrolls-in-body {
  source: selector(body);
  scroll-offsets:
    selector(#cards) start 1, /* Start when the start edge touches the top of the scrollport */
    selector(#cards) start 0 /* End when the start edge touches the start of the scrollport */
  ;
  time-range: 4s;
}

.card {
  --index0: calc(var(--index) - 1); /* 0-based index */
  --reverse-index: calc(var(--numcards) - var(--index0)); /* reverse index */
  --reverse-index0: calc(var(--reverse-index) - 1); /* 0-based reverse index */
}

@keyframes scale {
  to {
    transform: scale(calc(1.1 - calc(0.1 * var(--reverse-index))));
  }
}
	
.card__content {
  transform-origin: 50% 0%;
  will-change: transform;

  --duration: calc(var(--reverse-index0) * 1s);
  --delay: calc(var(--index0) * 1s);
  
  animation: var(--duration) linear scale var(--delay) forwards;
  animation-timeline: cards-element-scrolls-in-body;
}

At first I struggled a lot with getting the sticky part right, as my position: sticky; would work as expected, but not as I wanted: the last card slid over the preceding ones:

After doing a detour with manually trying to translate the cards, I eventually found how to get my position: sticky; to work as I wanted.

  1. Don’t vary top by an extra 1em per sticky item, but fixate top: 0; and adjust the padding-top to achieve the offset.
  2. Lay out all cards in their wrapper using CSS Grid with fixated rows. Their padding simply bleeds out (huh? 🤯), and therefore they will be evenly spaced using gap.

Cool part is: browsers that don’t understand @​scroll-timeline but do speak position: sticky; will also see the effect, but simply without the scaling.

~

# In Closing

With those fine demos we conclude this second part of this series! We’ve covered how to create Scroll-Linked Animations based on the location of an element within the scroller, and how we can tweak their offsets. I think it’s pretty amazing what we can do with them … the amount of JavaScript that can be replaced with it will be huge.

I hope I’ve been able to get you excited for this possible future addition to CSS throughout this post. Although it still is in its very early stages, I’m confident this will become a CSS WG Recommendation one day 🙂

I’m glad to see that the Chromium engineers are actively working on this experimental implementation, taking the time to respond to newly reported bugs. I hope that other browser vendors will follow suit soon. Relevant tracking bugs to flag/star/follow:

🗃 You can find all demos shown in this post over at CodePen, in a Collection Scroll-Linked Animations: Part 2. It’d be great if you could ❤️ the collection and/or the demos you like.

~

To help spread the contents of this post, feel free to retweet its announcement tweet:

Follow @bramus (= me, the author) and/or @bramusblog (= the feed of this blog) on Twitter to stay-up-to date with future posts. RSS also available.

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

Control the behavior of JavaScript imports with Import Maps

Shipping in Chrome 89 are Import Maps, which allows control over what URLs get fetched when importing modules.

Let’s take a look at this very welcome addition.

When importing ES Modules (on the web), you need to refer to them using their full filenames or URLs:

import moment from "/js/moment/moment.js";
import { partition } from "/js/lodash-es/lodash.js";

In a Node environment however, you would write the snippet above as follows:

import moment from "moment";
import { partition } from "lodash";

(Node will map things to the /node_modules folder all by itself)

👉 So depending on where you run your code, your import statements need to change. Meh.

~

Thankfully Import Maps provide a solution to this. They allow you to specify which file/URL should be loaded when importing a package.

{
  "imports": {
    "moment": "/js/moment/moment.js",
    "lodash": "/js/lodash-es/lodash.js"
  }
}

With this in place the browser can handle import { partition } from "lodash" just fine, as it will load the file /js/lodash-es/lodash.js. 🎉

💡 With services like Skypack in place I can already see tools pop up that would automate the generation of such an import map based on a package[-lock].json that you feed it.

~

An import map is a tad of JSON file which you need to put it in a script[type="importmap"] element:

<script type="importmap">
{
  "imports": {
    "moment": "/js/moment/moment.js",
    "lodash": "/js/lodash-es/lodash.js"
  }
}
</script>

☝️ In the future it’ll also be possible to to put your import map into an external file and load it by specifying an src

<script type="importmap" src="import-map.importmap"></script>

To play nice with Content-Security Policy (CSP) the server needs to send the proper MIME-type though:

application/importmap+json

For more advanced usage, it’s also possible to add scoping.

~

These Import Maps sure are a very welcome addition. Unfortunately browser support is currently limited to Chrome only.

Data on support for the import-maps feature across the major browsers from caniuse.com

💡 Shown above is a dynamic CanIUse.com image, showing an always up-to-date support table. By the time you are reading this browser support might have become better.

Let’s hope other browsers follow suit soon. Relevant bugs to track:

~

To help spread the contents of this post, feel free to retweet its announcement tweet:

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

The Future of CSS: Scroll-Linked Animations with @scroll-timeline (Part 1)

Example of what is possible with Scroll-Linked Animations, using only CSS

The Scroll-linked Animations Specification is an upcoming addition to CSS that defines a way for creating animations that are linked to a scroll offset of a scroll container. Even though the specification is still in draft, and in no way finalized nor official, it already has experimental support in Chromium.

The past few weeks I’ve been playing with the CSS @scroll-timeline at-rule and the animation-timeline CSS property this specification provides. By combining these two features with regular CSS Animations we can create Scroll-Linked Animations using only CSS — not a single line of JavaScript in sight!

In this first part of this series we’ll take a look at Scroll-Linked Animations between two absolute scroll-offsets, and how we can tweak them. In the second part of this series (published here) we’ll cover how to create Scroll-Linked Animations based on the location of an element within the scroller.

~

👨‍🔬 The CSS features described in this post are still experimental and not finalized at all! If you’re feeling adventurous you can play with these new features today, but you’ll need at least Chromium 89 with the #experimental-web-platform-features flag enabled through chrome://flags.

💥 To keep your primary Chrome install clean, I recommend you do not set this in Chrome Stable, but resort to Beta / Canary builds.

👀 If you don’t understand how to do this, or don’t feel safe doing this, fear not: This post also includes recordings and/or fallback versions using JavaScript for most of the demos.

💄 While the Scroll-Linked Animations Specification also describes a JavaScript interface, the main focus of this post will be its CSS counterpart. The JS alternatives won’t be covered in detail.

~

Table of Contents

  1. Primer: Scroll-Linked Animations vs. Scroll-Triggered Animations
  2. Your first Scroll-Linked Animation (Progress Bar Demo)
  3. Tweaking the Offsets (Parallax Cover Demo)
  4. Changing the Scroll Orientation
  5. Changing the Scroll Container (In-Page Gallery Demo)
  6. In-Between Summary
  7. More Demos
    1. Parallax Cover to Sticky Header Demo
    2. Full Screen Panels with Snap Points Demo
    3. Full Screen Panels with Snap Points Demo, With Navigation Controls
  8. In Closing

~

# Primer: Scroll-Linked Animations vs. Scroll-Triggered Animations

Before we jump into the CSS code, there’s this difference that we need to make between Scroll-Linked Animations and Scroll-Triggered Animations

Scroll-Linked Animations are animations are linked to the scroll offset of a scroll container. As you scroll back and forth the scroll container, you will see the animation timeline advance or rewind as you do so. If you stop scrolling, the animation will also stop.

Think of a progress bar shown on top of a page, where there is a direct link between the scroll progress and size of the progress bar. Hit the ⏮ and ⏭ buttons in the visualization below to see how it behaves.

See the Pen Scroll-Linked Animations Visualization: Progressbar by Bramus (@bramus) on CodePen.

Using Scroll-Linked Animations you can animate elements as a scroll container scrolls.

Scroll-Triggered Animations are animations that are triggered when scrolling past a certain position. Once triggered, these animations start and finish on their own, independent of whether you keep scrolling or not.

Think of those typical “content flies in as it enters the viewport” animations. Hit the ⏮ and ⏭ buttons in the visualization below to see how it behaves.

See the Pen Scroll-Triggered Animations Visualization: Fly-In Content by Bramus (@bramus) on CodePen.

Using Scroll-Triggered Animations you can animate elements as they enter/exit the scrollport

~

# Your first Scroll-Linked Animation (Progress Bar Demo)

Instead of getting technical straight away, let’s take a look at a Progress Bar that is implemented using Scroll-Linked Animations, and dissect it from there.

What you see there — if your browser supports it — is a scrollbar that progresses from 0 to 100% as you scroll down the page. All this is done using only CSS, and running in a non-blocking way on the compositor thread (e.g. “off main thread”)! 🤩

Apart from positioning and what not, the code that drives this demo is this little piece of CSS:

/* (1) Define Keyframes */
@keyframes adjust-progressbar {
    from {
        transform: scaleX(0);
    }
    to {
        transform: scaleX(1);
    }
}

/* (2) Define a ScrollTimeline */
@scroll-timeline progressbar-timeline {
    time-range: 1s;
}

/* (3) Attach the Animation + set the ScrollTimeline as the driver for the Animation */
#progressbar {
    animation: 1s linear forwards adjust-progressbar;
    animation-timeline: progressbar-timeline; /* 👈 THIS! */
}

We recognise 3 key components that we need to make it all work:

  1. An Animation
  2. A Scroll Timeline
  3. A way to link both

~

# The Animation

This is a a regular CSS Animation. In case of our progress bar it’s an animation that goes from zero width to full width.

@keyframes adjust-progressbar {
    from {
        transform: scaleX(0);
    }
    to {
        transform: scaleX(1);
    }
}

#progressbar {
    width: 100vw;
    transform: scaleX(0);
    transform-origin: 0 50%;
    animation: 1s linear forwards adjust-progressbar;
}

There’s a few things to note about this animation:

  • To optimize this animation for the browser we don’t animate the width property, but fixate the width to 100vw and animate transform: scaleX(…); instead. To make that work properly we have to set the transform-origin to the left edge of the element.
  • To prevent a FOUC we apply the start scaleX(0); transform directly onto the #progressbar element.
  • To make sure this animation remains in its end state when it has finished, we set animation-fill-mode to forwards.
  • The values for animation-duration (1s) and animation-timing-function (linear) look like they are chosen arbitrarily here, but they’re not. We’ll dig into these further down.

Now, if you implement this piece of CSS as-is, you’ll see this animation run all by itself. This is because we have not created nor linked a Scroll Timeline yet, which follow next.

~

# The Scroll Timeline

As we scroll through the document from top to bottom (e.g. from 0% to 100%) we want our animation to also go from start to finish (e.g. from 0s to 1s). For this we need a Scroll Timeline. It is a type of timeline whose actual time value is determined by the progress of scrolling in a scroll container.

To define a ScrollTimeline in CSS, we can use the new @scroll-timeline at-rule, and configure it using descriptors:

  1. source
  2. orientation
  3. scroll-offsets
  4. time-range

For our Progress Bar we only need the time-range descriptor to make it work, and it looks like this:

@scroll-timeline progress-timeline {
    time-range: 1s;
}

Here we have created a Scroll Timeline with the name progress-timeline. The value set for the time-range descriptor is a CSS <time> Data Type. In this case here it does not represent the time of a clock though, but is a number that maps Scroll Progress to Animation Progress. It gives an answer to the question “How much animation time should pass when we scroll from start to finish in the scroll container?”

As we have defined our animation-duration to be 1s from start to finish, we want our time-range to reflect that same duration, namely 1s: Scrolling from top to bottom (e.g. from 0% to 100%) should advance the animation by 1s.

Our scroll-to-time mapping internally looks like this:

  • 0% Scroll Progress equals 0s Animation Progress.
  • 100% Scroll Progress equal s1s Animation Progress.

(All values in between are interpolated, so 50% Scroll Progress will equal 0.5s Animation Progress)

🔥 TIP: Always set time-range to the exact same time as the animation-duration, unless you have a very good reason not to.

🚨 It’s very important to understand that this time-range descriptor does not represent the time of a clock, but is nothing more than a mapping.

A few examples to make this more clear:

  • Say animation-duration + time-range are both 1s:

    • 0% of scrolling maps to 0s of the timeline
    • 100% of scrolling maps to 1s of the timeline

    👉 In this case the animation will go from start to finish a you scroll from top to bottom.

  • Say animation-duration is 1s and time-range is 2s:

    • 0% of scrolling maps to 0s of the timeline
    • 100% of scrolling maps to 2s of the timeline

    👉 Here the animation will go twice as fast as you scroll to the bottom. E.g. if you’re halfway in the scroll container, the animation will already be complete!

~

# Linking up both

To associate our @scroll-timeline with our CSS Animation we use the new animation-timeline CSS property, and have it refer to the timeline’s name.

#progressbar {
    animation: 1s linear forwards adjust-progressbar;
    animation-timeline: progressbar-timeline; /* 👈 THIS! */
}

This is the part where our animation-timing value of linear comes into play: it enforces a 1-on-1 mapping between Scroll Progress and Animation Progress. If we were to set our timing to something like ease-in instead, we’d see our progress bar be too slow at the beginning and speed up towards the end as we scroll. This feels really weird to be honest.

🔥 TIP: Always set animation-timing-function to linear when working with @scroll-timeline.

~

# Tweaking the Offsets (Parallax Cover Demo)

By default a @scroll-timeline will be linked to scrolling vertically from top to bottom across the document. But what if we our animation to start/stop when having scrolled for a specific (~ fixed) distance? This is where the scroll-offsets descriptor comes into play.

😵 As reader Patrick H Lauke points out you might want to go easy with the type of animation shown below in case visitors request so, by respecting the setting of prefers-reduced-motion.

In this example we have a full-page (100vh) parallax cover. For it to work correctly we want our animation to begin at the start of the document and to be finished after scrolling 100vh into the document (instead of the default “100% of the document”).

To make this happen we set our Scroll Offsets to 0 (start) and 100vh (end). The resulting @scroll-timeline definition looks like this:

@scroll-timeline parallax-header-timeline {
    scroll-offsets: 0%, 100vh;
    time-range: 1s;
}

You can put any <length> or <percentage> Data Type in there.

☝️ In an earlier version of the spec one had to define the Scroll Offsets using start and end descriptors.

@scroll-timeline parallax-header-timeline {
    start: 0%;
    end: 100vh;
    time-range: 1s;
}

This is no longer the case, and one should now use the scroll-offsets descriptor instead.

However, you might still see this older syntax in the demos as Chromium has this older version implemented and is in the process of migrating to the new scroll-offsets syntax — Relevant Chromium Bug: 1094014

If you want, you can also put in more than two values, but note that your scroll to time mapping might become wonky. With scroll-offsets: 0vh, 80vh, 100vh; and a time-range of 1s for example, your scroll-time map will become this:

  • At 0vh your time-range will have advanced to 0s
  • At 80vh your time-range will have advanced to 0.5s, as that 80vh is defined “halfway the array of values”
  • At 100vh your time-range will have advanced to 1s
🔥 TIP: Always set two values for scroll-offsets, unless you have a specific reason not to.

☝️ The scroll-offsets can accept more types of values, which we will cover further down this post.

~

# Changing the Scroll Orientation

By default a @scroll-timeline will be linked to scrolling vertically from top to bottom across the document. Using the orientation descriptor we can change this to — for example — horizontal.

@scroll-timeline example {
    orientation: horizontal;
    time-range: 1s;
}

Use of the logical values inline and block is also allowed. Finally, there’s also auto.

~

# Changing the Scroll Container (In-Page Gallery Demo)

By default a @scroll-timeline will be linked to scrolling vertically from top to bottom across the document. But what if we don’t want across the document, but inside a specific element? This is where the source descriptor comes into play.

Below is an example that contains two in-page image galleries/carousels, implemented using scroll-snapping. Each of those have a progress bar attached. To drive these progress bars we need not want to respond to scroll progress in the document, but to scrolling in their own scroll container.

To define which scroll container a @scroll-timeline responds to, you need set the source descriptor, and have it target said element. To do so you can use the selector() function as its value. That function requires an <id-selector>, so you’ll need to give your targeted element an id attribute value.

@scroll-timeline example {
    source: selector(#foo);
    time-range: 1s;
}

As we have two galleries, we need to define two @scroll-timeline instances and connect them to their proper progress bar. And since they are horizontally scrolling ones, we also need to set the orientation descriptor correctly. Our code eventually looks like this:

<div class="gallery" id="gallery1">
    <div class="gallery__progress" id="gallery1__progress"></div>
    <div class="gallery__scrollcontainer" id="gallery1__scrollcontainer">
        <div class="gallery__entry">
            …
        </div>
        <div class="gallery__entry">
            …
        </div>
    </div>
</div>
@keyframes progress {
	to {
		transform: scaleX(1);
	}
}

/* #gallery1 */
@scroll-timeline gallery1__timeline {
	source: selector(#gallery1__scrollcontainer);
	orientation: horizontal;
	time-range: 1s;
}
#gallery1__progress {
	/* We have 2 photos, with the 1st visible, so we start at 1/2 */
	transform: scaleX(0.5);
	animation: 1s linear forwards progress;
	animation-timeline: gallery1__timeline;
}

/* #gallery2 */
@scroll-timeline gallery2__timeline {
	source: selector(#gallery2__scrollcontainer);
	orientation: horizontal;
	time-range: 1s;
}
#gallery2__progress {
	/* We have 3 photos, with the 1st visible, so we start at 1/3 */
	transform: scaleX(0.333);
	animation: 1s linear forwards progress;
	animation-timeline: gallery2__timeline;
}

😖 One thing I find pretty annoying when it comes to this selector() function is that you must pass an id into it. This can become pretty cumbersome: with 10 galleries on a page, you need to define 10 almost identical @scroll-timelines in your code. Only difference between them: the id passed into selector().

I consider this to be shortcoming of the specification, and have raised an issue with the CSSWG: it would be handy if selector() could point to the current element being animated or would accept any selector. That way you can reuse one single @scroll-timeline on multiple elements.

Relevant CSS WG Issue: 5884

💡 If you think you would be able to dynamically set the <id-selector> in source by means of CSS Custom Property, don’t bother: CSS Variables cannot be used within descriptors.

~

# In-Between Summary

📝 Before we continue with the really cool stuff that’s coming up, let’s summarize what we know so far.

A Scroll Timeline is an interface that lets us map Scroll Progress to Animation Progress. You can define it in CSS using @scroll-timeline with the following descriptors:

source
The scrollable element whose scrolling triggers the activation and drives the progress of the timeline.
orientation
The direction of scrolling which triggers the activation and drives the progress of the timeline.
scroll-offsets
An array of two or more scroll offsets that constitute the in-progress intervals in which the timeline is active.
time-range
A duration that maps the amount scrolled between the Scroll Offsets to the duration of an animation.

Allowed values for the descriptors:

  • By default the source is the document’s scrolling element (value: auto), but you can also target an element using selector(<id-selector>)
  • The orientation is vertical or horizontal. Using logical units inline and block is also possible. The initial value is auto.
  • Typically the entries in scroll-offsets are lengths or percentages, but we’ll cover an extra variation in the next part
  • Easiest setting for time-range is the same value as the animation’s animation-duration.

To attach a @scroll-timeline to an animation, use the animation-timeline property.

~

# More Demos

As I have been playing with CSS @scroll-timeline for nearly a month by now, I’ve been making quite a lot of demos. Here’s a fine selection relevant for this first part of this series:

  1. Parallax Cover to Sticky Header Demo
  2. Full Screen Panels with Snap Points Demo
  3. Full Screen Panels with Snap Points Demo, With Navigation Controls

~

# Parallax Cover to Sticky Header Demo

Building further upon the Parallax Cover from earlier on, here’s a demo that converts a full page Cover Image to a Sticky Header.

The @scroll-timeline is exactly the same as the Parallax Cover demo, only the animation is a bit different: the color, font-size, and height are also adjusted upon scrolling.

I couldn’t use position: sticky; here though, as resizing the cover would shrink down the entire height of the document, and therefore the animation would flicker. Instead I resorted to position: fixed; and added a margin-top of 100vh to the text content so that it remains visually below the cover.

~

# Full Screen Panels with Snap Points Demo

This is a small demo forked from this demo by Adam Argyle, which put CSS @scroll-timeline on my radar (thanks, Adam!). The page features a 4-panel full-page carousel with numbers that slide into view.

The demo has been adjusted to use CSS @scroll-timeline and mix-blend-mode: difference;.

The / 4 suffix is position: fixed; on the page, and the / character inside spins around 1turn per panel that you scroll. As there are 4 panels in total, we spin for a total of 3turn from top to bottom of the scroll container.

@scroll-timeline spin-slash {
  source: selector(#main);  
  time-range: 1s;
}

@keyframes rotato {
  to {
    transform: rotateZ(3turn);
  }
}

.slash {
  animation: rotato 1s linear;
  animation-timeline: spin-slash;
}

~

# Full Screen Panels with Snap Points Demo, With Navigation Controls

This demo builds further upon the previous one and adds a navigation bar to it. The active indicator is powered by @scroll-timeline: as you scroll through #main, the active indicator moves to the correct navigation item.

There are two variants for you to check:

  1. There is one single active indicator shared amongst all navigation items.
  2. Each navigation item has its own active indicator.

I like how in this second example these indicators reflect the percentage each section is in view (or not).

In the first version a line is injected underneath the navigation and its left position is adjusted using the same @scroll-timeline as the panels use.

In the second version each navigation item gets a line injected. The animation to show/hide the line is one shared animation for all items that does both the showing and the hiding:

@keyframes reveal-indicator {
  1% { /* We use 1% instead of 0% to prevent rounding/rendering glitches */
    transform: scaleX(0);
  }
  50% {
    transform: scaleX(1);
  }
  99% {  /* We use 99% instead of 100% to prevent rounding/rendering glitches */
    transform: scaleX(0);
  }
}

Now it gets tricky though: for each navigation item we create a different @scroll-timeline whose scroll-offsets and time-range vary.

  • The default time-range is 4s
  • The first and last items only need half an animation though (as you can’t scroll past them) so their time-range is set to 2s
  • To fix the first item’s animation we use a negative animation-delay of -2s on the element itself. That way it’s animation will start “too soon”, and will already be at 50% (thus at scaleX(1)) on page load.

~

# In Closing

That’s it for the first part of this series! We’ve covered how to create Scroll-Linked Animations between two absolute scroll-offsets, and how we can tweak our defined @scroll-timelines.

🔥 In the second part of this series (published here) we cover how to create Scroll-Linked Animations based on the location of an element within the scroller.

Follow @bramus (= me, the author) and/or @bramusblog (= the feed of this blog) on Twitter to stay-up-to date with future posts. RSS also available.

I hope I’ve been able to get you excited for this possible future addition to CSS throughout this post. Although it still is in its very early stages, I’m confident this will become a CSS WG Recommendation one day 🙂

I’m glad to see that the Chromium engineers are actively working on this experimental implementation, taking the time to respond to newly reported bugs. I hope that other browser vendors will follow suit soon. Relevant tracking bugs to flag/star/follow:

🗃 You can find all demos shown in this post over at CodePen, in a Collection Scroll-Linked Animations: Part 1. It’d be great if you could ❤️ the collection and/or the demos you like.

~

To help spread the contents of this post, feel free to retweet its announcement tweet:

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

Style Spelling and Grammar Errors with the ::spelling-error and ::grammar-error pseudo-elements

Part of the CSS Pseudo-Elements Level 4 Specification are ways to style spelling and grammar errors.

By default spelling errors — words you have mistyped — get a red dotted underline, thanks to the ::spelling-error pseudo-class selector you can tweak that. Grammar errors — such as a missing capital letter at the beginning of a sentence — can be styled with the ::grammar-error pseudo-class selector.

::spelling-error {
  text-decoration: underline wavy red;
}

::grammar-error {
  text-decoration: underline wavy blue;
}

~

Embedded below is a demo that shows the output of the browser you are visiting with, and the wanted output:


See the Pen The Future of CSS: Style Grammar and Spelling Errors (Demo) by Bramus (@bramus) on CodePen.

As you can see your browser does not yield the proper output, as ::spelling-error/::grammar-error currently have no support in any browser at the time of writing:

~

Once these highlight pseudo-elements do gain browser support, do note that they can only be styled by a limited set of properties that do not affect layout. Only following properties apply to the highlight pseudo-elements:

  • color
  • background-color
  • text-decoration and its associated properties
  • text-shadow
  • stroke-color, fill-color, and stroke-width

~

In case you are interested, here are the relevant bugs to flag/star/follow:

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

~

Style the target text from text-fragment links using the ::target-text pseudo-element

One of my favorite features that shipped with Chrome 80 — apart from Optional Chaining — is the ability to link to text-fragments. By default Chrome will highlight those in yellow:

~

As tweeted before, coming to Chromium 89 is the ability to style those text-fragments using the ::target-text pseudo-element, which is part of the CSS Pseudo-Elements Level 4 Specification.

This snippet below:

/* Style scroll-to-text fragments */
::target-text {
    background: #00cdff;
}

Will visually manifest itself like this:

~

Note that the ::target-text pseudo-element can only be styled by a limited set of properties that do not affect layout. Only following properties apply:

  • color
  • background-color
  • text-decoration and its associated properties
  • text-shadow
  • stroke-color, fill-color, and stroke-width

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

Apache .htaccess disable access to site during Maintenance Mode / Deployment

Because I have to look this up from time to time, a note to myself: Add the contents below to your .htaccess to have Apache respond with a “Temporarily Unavailable” message in case a .maintenance file exists. — Handy during deploys

RewriteEngine On

# Show "Temporarily Unavailable" page if there's a .maintenance file present
RewriteCond %{DOCUMENT_ROOT}/.maintenance -f
RewriteRule .* - [R=503,L]

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.