Web Standards
Unleash the Power of Scroll-Driven Animations
I’m utterly behind in learning about scroll-driven animations apart from the “reading progress bar” experiments all over CodePen. Well, I’m not exactly “green” on the topic; we’ve published a handful of articles on it including this neat-o one by Lee Meyer published the other week.
Our “oldest” article about the feature is by Bramus, dated back to July 2021. We were calling it “scroll-linked” animation back then. I specifically mention Bramus because there’s no one else working as hard as he is to discover practical use cases where scroll-driven animations shine while helping everyone understand the concept. He writes about it exhaustively on his personal blog in addition to writing the Chrome for Developers documentation on it.
But there’s also this free course he calls “Unleash the Power of Scroll-Driven Animations” published on YouTube as a series of 10 short videos. I decided it was high time to sit, watch, and learn from one of the best. These are my notes from it.
Introduction- A scroll-driven animation is an animation that responds to scrolling. There’s a direct link between scrolling progress and the animation’s progress.
- Scroll-driven animations are different than scroll-triggered animations, which execute on scroll and run in their entirety. Scroll-driven animations pause, play, and run with the direction of the scroll. It sounds to me like scroll-triggered animations are a lot like the CSS version of the JavaScript intersection observer that fires and plays independently of scroll.
- Why learn this? It’s super easy to take an existing CSS animation or a WAAPI animation and link it up to scrolling. The only “new” thing to learn is how to attach an animation to scrolling. Plus, hey, it’s the platform!
- There are also performance perks. JavsScript libraries that establish scroll-driven animations typically respond to scroll events on the main thread, which is render-blocking… and JANK! We’re working with hardware-accelerated animations… and NO JANK. Yuriko Hirota has a case study on the performance of scroll-driven animations published on the Chrome blog.
- Supported in Chrome 115+. Can use @supports (animation-timeline: scroll()). However, I recently saw Bramus publish an update saying we need to look for animation-range support as well.
- Remember to use prefers-reduced-motion and be mindful of those who may not want them.
Let’s take an existing CSS animation.
@keyframes grow-progress { from { transform: scaleX(0); } to { transform: scaleX(1); } } #progress { animation: grow-progress 2s linear forwards; }Translation: Start with no width and scale it to its full width. When applied, it takes two seconds to complete and moves with linear easing just in the forwards direction.
This just runs when the #progress element is rendered. Let’s attach it to scrolling.
- animation-timeline: The timeline that controls the animation’s progress.
- scroll(): Creates a new scroll timeline set up to track the nearest ancestor scroller in the block direction.
That’s it! We’re linked up. Now we can remove the animation-duration value from the mix (or set it to auto):
#progress { animation: grow-progress linear forwards; animation-timeline: scroll(); }Note that we’re unable to plop the animation-timeline property on the animation shorthand, at least for now. Bramus calls it a “reset-only sub-property of the shorthand” which is a new term to me. Its value gets reset when you use the shorthand the same way background-color is reset by background. That means the best practice is to declare animation-timeline after animation.
/* YEP! */ #progress { animation: grow-progress linear forwards; animation-timeline: scroll(); } /* NOPE! */ #progress { animation-timeline: scroll(); animation: grow-progress linear forwards; }Let’s talk about the scroll() function. It creates an anonymous scroll timeline that “walks up” the ancestor tree from the target element to the nearest ancestor scroll. In this example, the nearest ancestor scroll is the :root element, which is tracked in the block direction.
We can name scroll timelines, but that’s in another video. For now, know that we can adjust which axis to track and which scroller to target in the scroll() function.
animation-timeline: scroll(<axis> <scroller>);- <axis>: The axis — be it block (default), inline, y, or x.
- <scroller>: The scroll container element that defines the scroll position that influences the timeline’s progress, which can be nearest (default), root (the document), or self.
If the root element does not have an overflow, then the animation becomes inactive. WAAPI gives us a way to establish scroll timelines in JavaScript with ScrollTimeline.
const $progressbar = document.querySelector(#progress); $progressbar.style.transformOrigin = '0% 50%'; $progressbar.animate( { transform: ['scaleX(0)', 'scaleY()'], }, { fill: 'forwards', timeline: new ScrollTimeline({ source: document.documentElement, // root element // can control `axis` here as well }), } ) Video Two Core Concepts: view() and ViewTimelineFirst, we oughta distinguish a scroll container from a scroll port. Overflow can be visible or clipped. Clipped could be scrolling.
Those two bordered boxes show how easy it is to conflate scrollports and scroll containers. The scrollport is the visible part and coincides with the scroll container’s padding-box. When a scrollbar is present, that plus the scroll container is the root scroller, or the scroll container.
A view timeline tracks the relative position of a subject within a scrollport. Now we’re getting into IntersectionObserver territory! So, for example, we can begin an animation on the scroll timeline when an element intersects with another, such as the target element intersecting the viewport, then it progresses with scrolling.
Bramus walks through an example of animating images in long-form content when they intersect with the viewport. First, a CSS animation to reveal an image from zero opacity to full opacity (with some added clipping).
@keyframes reveal { from { opacity: 0; clip-path: inset(45% 20% 45% 20%); } to { opacity: 1; clip-path: inset(0% 0% 0% 0%); } } .revealing-image { animation: reveal 1s linear both; }This currently runs on the document’s timeline. In the last video, we used scroll() to register a scroll timeline. Now, let’s use the view() function to register a view timeline instead. This way, we’re responding to when a .revealing-image element is in, well, view.
.revealing-image { animation: reveal 1s linear both; /* Rember to declare the timeline after the shorthand */ animation-timeline: view(); }At this point, however, the animation is nice but only completes when the element fully exits the viewport, meaning we don’t get to see the entire thing. There’s a recommended way to fix this that Bramus will cover in another video. For now, we’re speeding up the keyframes instead by completing the animation at the 50% mark.
@keyframes reveal { from { opacity: 0; clip-path: inset(45% 20% 45% 20%); } 50% { opacity: 1; clip-path: inset(0% 0% 0% 0%); } }More on the view() function:
animation-timeline: view(<axis> <view-timeline-inset>);We know <axis> from the scroll() function — it’s the same deal. The <view-timeline-inset> is a way of adjusting the visibility range of the view progress (what a mouthful!) that we can set to auto (default) or a <length-percentage>. A positive inset moves in an outward adjustment while a negative value moves in an inward adjustment. And notice that there is no <scroller> argument — a view timeline always tracks its subject’s nearest ancestor scroll container.
OK, moving on to adjusting things with ViewTimeline in JavaScript instead.
const $images = document.querySelectorAll(.revealing-image); $images.forEach(($image) => { $image.animate( [ { opacity: 0, clipPath: 'inset(45% 20% 45% 20%)', offset: 0 } { opacity: 1; clipPath: 'inset(0% 0% 0% 0%)', offset: 0.5 } ], { fill: 'both', timeline: new ViewTimeline({ subject: $image, axis: 'block', // Do we have to do this if it's the default? }), } } )This has the same effect as the CSS-only approach with animation-timeline.
Video Three Timeline Ranges DemystifiedLast time, we adjusted where the image’s reveal animation ends by tweaking the keyframes to end at 50% rather than 100%. We could have played with the inset(). But there is an easier way: adjust the animation attachment range,
Most scroll animations go from zero scroll to 100% scroll. The animation-range property adjusts that:
animation-range: normal normal;Those two values: the start scroll and end scroll, default:
animation-range: 0% 100%;Other length units, of course:
animation-range: 100px 80vh;The example we’re looking at is a “full-height cover card to fixed header”. Mouthful! But it’s neat, going from an immersive full-page header to a thin, fixed header while scrolling down the page.
@keyframes sticky-header { from { background-position: 50% 0; height: 100vh; font-size: calc(4vw + 1em); } to { background-position: 50% 100%; height: 10vh; font-size: calc(4vw + 1em); background-color: #0b1584; } }If we run the animation during scroll, it takes the full animation range, 0%-100%.
.sticky-header { position: fixed; top: 0; animation: sticky-header linear forwards; animation-timeline: scroll(); }Like the revealing images from the last video, we want the animation range a little narrower to prevent the header from animating out of view. Last time, we adjusted the keyframes. This time, we’re going with the property approach:
.sticky-header { position: fixed; top: 0; animation: sticky-header linear forwards; animation-timeline: scroll(); animation-range: 0vh 90vh; }We had to subtract the full height (100vh) from the header’s eventual height (10vh) to get that 90vh value. I can’t believe this is happening in CSS and not JavaScript! Bramus sagely notes that font-size animation happens on the main thread — it is not hardware-accelerated — and the entire scroll-driven animation runs on the main as a result. Other properties cause this as well, notably custom properties.
Back to the animation range. It can be diagrammed like this:
The animation “cover range”. The dashed area represents the height of the animated target element.Notice that there are four points in there. We’ve only been chatting about the “start edge” and “end edge” up to this point, but the range covers a larger area in view timelines. So, this:
animation-range: 0% 100%; /* same as 'normal normal' */…to this:
animation-range: cover 0% cover 100%; /* 'cover normal cover normal' */…which is really this:
animation-range: cover;So, yeah. That revealing image animation from the last video? We could have done this, rather than fuss with the keyframes or insets:
animation-range: cover 0% cover 50%;So nice. The demo visualization is hosted at scroll-driven-animations.style. Oh, and we have keyword values available: contain, entry, exit, entry-crossing, and exit-crossing.
contain entry exitThe examples so far are based on the scroller being the root element. What about ranges that are taller than the scrollport subject? The ranges become slightly different.
Just have to be aware of the element’s size and how it impacts the scrollport.This is where the entry-crossing and entry-exit values come into play. This is a little mind-bendy at first, but I’m sure it’ll get easier with use. It’s clear things can get complex really quickly… which is especially true when we start working with multiple scroll-driven animation with their own animation ranges. Yes, that’s all possible. It’s all good as long as the ranges don’t overlap. Bramus uses a contact list demo where contact items animate when they enter and exit the scrollport.
@keyframes animate-in { 0% { opacity: 0; transform: translateY: 100%; } 100% { opacity: 1; transform: translateY: 0%; } } @keyframes animate-out { 0% { opacity: 1; transform: translateY: 0%; } 100% { opacity: 0; transform: translateY: 100%; } } .list-view li { animation: animate-in linear forwards, animate-out linear forwards; animation-timeline: view(); animation-range: entry, exit; /* animation-in, animation-out */ }Another way, using entry and exit keywords directly in the keyframes:
@keyframes animate-in { entry 0% { opacity: 0; transform: translateY: 100%; } entry 100% { opacity: 1; transform: translateY: 0%; } } @keyframes animate-out { exit 0% { opacity: 1; transform: translateY: 0%; } exit 100% { opacity: 0; transform: translateY: 100%; } } .list-view li { animation: animate-in linear forwards, animate-out linear forwards; animation-timeline: view(); }Notice that animation-range is no longer needed since its values are declared in the keyframes. Wow.
OK, ranges in JavaScript.:
const timeline = new ViewTimeline({ subjext: $li, axis: 'block', }) // Animate in $li.animate({ opacity: [ 0, 1 ], transform: [ 'translateY(100%)', 'translateY(0)' ], }, { fill: 'forwards', // One timeline instance with multiple ranges timeline, rangeStart: 'entry: 0%', rangeEnd: 'entry 100%', }) Video Four Core Concepts: Timeline Lookup and Named TimelinesThis time, we’re learning how to attach an animation to any scroll container on the page without needing to be an ancestor of that element. That’s all about named timelines.
But first, anonymous timelines track their nearest ancestor scroll container.
<html> <!-- scroll --> <body> <div class="wrapper"> <div style="animation-timeline: scroll();"></div> </div> </body> </html>Some problems might happen like when overflow is hidden from a container:
<html> <!-- scroll --> <body> <div class="wrapper" style="overflow: hidden;"> <!-- scroll --> <div style="animation-timeline: scroll();"></div> </div> </body> </html>Hiding overflow means that the element’s content block is clipped to its padding box and does not provide any scrolling interface. However, the content must still be scrollable programmatically meaning this is still a scroll container. That’s an easy gotcha if there ever was one! The better route is to use overflow: clip rather than hidden because that prevents the element from becoming a scroll container.
Hiding oveflow = scroll container. Clipping overflow = no scroll container. Bramus says he no longer sees any need to use overflow: hidden these days unless you explicitly need to set a scroll container. I might need to change my muscle memory to make that my go-to for hiding clipping overflow.
Another funky thing to watch for: absolute positioning on a scroll animation target in a relatively-positioned container. It will never match an outside scroll container that is scroll(inline-nearest) since it is absolute to its container like it’s unable to see out of it.
We don’t have to rely on the “nearest” scroll container or fuss with different overflow values. We can set which container to track with named timelines.
.gallery { position: relative; } .gallery__scrollcontainer { overflow-x: scroll; scroll-timeline-name: --gallery__scrollcontainer; scroll-timeline-axis: inline; /* container scrolls in the inline direction */ } .gallery__progress { position: absolute; animation: progress linear forwards; animation-timeline: scroll(inline nearest); }We can shorten that up with the scroll-timeline shorthand:
.gallery { position: relative; } .gallery__scrollcontainer { overflow-x: scroll; scroll-timeline: --gallery__scrollcontainer inline; } .gallery__progress { position: absolute; animation: progress linear forwards; animation-timeline: scroll(inline nearest); }Note that block is the scroll-timeline-axis initial value. Also, note that the named timeline is a dashed-ident, so it looks like a CSS variable.
That’s named scroll timelines. The same is true of named view timlines.
.scroll-container { view-timeline-name: --card; view-timeline-axis: inline; view-timeline-inset: auto; /* view-timeline: --card inline auto */ }Bramus showed a demo that recreates Apple’s old cover-flow pattern. It runs two animations, one for rotating images and one for setting an image’s z-index. We can attach both animations to the same view timeline. So, we go from tracking the nearest scroll container for each element in the scroll:
.covers li { view-timeline-name: --li-in-and-out-of-view; view-timeline-axis: inline; animation: adjust-z-index linear both; animation-timeline: view(inline); } .cards li > img { animation: rotate-cover linear both; animation-timeline: view(inline); }…and simply reference the same named timelines:
.covers li { view-timeline-name: --li-in-and-out-of-view; view-timeline-axis: inline; animation: adjust-z-index linear both; animation-timeline: --li-in-and-out-of-view;; } .cards li > img { animation: rotate-cover linear both; animation-timeline: --li-in-and-out-of-view;; }In this specific demo, the images rotate and scale but the updated sizing does not affect the view timeline: it stays the same size, respecting the original box size rather than flexing with the changes.
Phew, we have another tool for attaching animations to timelines that are not direct ancestors: timeline-scope.
timeline-scope: --example;This goes on an parent element that is shared by both the animated target and the animated timeline. This way, we can still attach them even if they are not direct ancestors.
<div style="timeline-scope: --gallery"> <div style="scroll-timeline: --gallery-inline;"> ... </div> <div style="animation-timeline: --gallery;"></div> </div>It accepts multiple comma-separated values:
timeline-scope: --one, --two, --three; /* or */ timeline-scope: all; /* Chrome 116+ */There’s no Safari or Firefox support for the all kewword just yet but we can watch for it at Caniuse (or the newer BCD Watch!).
This video is considered the last one in the series of “core concepts.” The next five are more focused on use cases and examples.
Video Five Add Scroll Shadows to a Scroll ContainerIn this example, we’re conditionally showing scroll shadows on a scroll container. Chris calls scroll shadows one his favorite CSS-Tricks of all time and we can nail them with scroll animations.
Here is the demo Chris put together a few years ago:
CodePen Embed FallbackThat relies on having a background with multiple CSS gradients that are pinned to the extremes with background-attachment: fixed on a single selector. Let’s modernize this, starting with a different approach using pseudos with sticky positioning:
.container::before, .container::after { content: ""; display: block; position: sticky; left: 0em; right 0em; height: 0.75rem; &::before { top: 0; background: radial-gradient(...); } &::after { bottom: 0; background: radial-gradient(...); } }The shadows fade in and out with a CSS animation:
@keyframes reveal { 0% { opacity: 0; } 100% { opacity: 1; } } .container { overflow:-y auto; scroll-timeline: --scroll-timeline block; /* do we need `block`? */ &::before, &::after { animation: reveal linear both; animation-timeline: --scroll-timeline; } }This example rocks a named timeline, but Bramus notes that an anonymous one would work here as well. Seems like anonymous timelines are somewhat fragile and named timelines are a good defensive strategy.
The next thing we need is to set the animation’s range so that each pseudo scrolls in where needed. Calculating the range from the top is fairly straightforward:
.container::before { animation-range: 1em 2em; }The bottom is a little tricker. It should start when there are 2em of scrolling and then only travel for 1em. We can simply reverse the animation and add a little calculation to set the range based on it’s bottom edge.
.container::after { animation-direction: reverse; animation-range: calc(100% - 2em) calc(100% - 1em); }Still one more thing. We only want the shadows to reveal when we’re in a scroll container. If, for example, the box is taller than the content, there is no scrolling, yet we get both shadows.
This is where the conditional part comes in. We can detect whether an element is scrollable and react to it. Bramus is talking about an animation keyword that’s new to me: detect-scroll.
@keyframes detect-scroll { from, to { --can-scroll: ; /* value is a single space and acts as boolean */ } } .container { animation: detect-scroll; animation-timeline: --scroll-timeline; animation-fill-mode: none; }Gonna have to wrap my head around this… but the general idea is that --can-scroll is a boolean value we can use to set visibility on the pseudos:
.content::before, .content::after { --vis-if-can-scroll: var(--can-scroll) visible; --vis-if-cant-scroll: hidden; visibility: var(--vis-if-can-scroll, var(--vis-if-cant-scroll)); }Bramus points to this CSS-Tricks article for more on the conditional toggle stuff.
Video Six Animate Elements in Different DirectionsThis should be fun! Let’s say we have a set of columns:
<div class="columns"> <div class="column reverse">...</div> <div class="column">...</div> <div class="column reverse">...</div> </div>The goal is getting the two outer reverse columns to scroll in the opposite direction as the inner column scrolls in the other direction. Classic JavaScript territory!
The columns are set up in a grid container. The columns flex in the column direction.
/* run if the browser supports it */ @supports (animation-timeline: scroll()) { .column-reverse { transform: translateY(calc(-100% + 100vh)); flex-direction: column-reverse; /* flows in reverse order */ } .columns { overflow-y: clip; /* not a scroll container! */ } }First, the outer columns are pushed all the way up so the bottom edges are aligned with the viewport’s top edge. Then, on scroll, the outer columns slide down until their top edges re aligned with the viewport’s bottom edge.
The CSS animation:
@keyframes adjust-position { from /* the top */ { transform: translateY(calc(-100% + 100vh)); } to /* the bottom */ { transform: translateY(calc(100% - 100vh)); } } .column-reverse { animation: adjust-position linear forwards; animation-timeline: scroll(root block); /* viewport in block direction */ }The approach is similar in JavaScript:
const timeline = new ScrollTimeline({ source: document.documentElement, }); document.querySelectorAll(".column-reverse").forEach($column) => { $column.animate( { transform: [ "translateY(calc(-100% + 100vh))", "translateY(calc(100% - 100vh))" ] }, { fill: "both", timeline, } ); } Video Seven Animate 3D Models and More on ScrollThis one’s working with a custom element for a 3D model:
<model-viewer alt="Robot" src="robot.glb"></model-viewer>First, the scroll-driven animation. We’re attaching an animation to the component but not defining the keyframes just yet.
@keyframes foo { } model-viewer { animation: foo linear both; animation-timeline: scroll(block root); /* root scroller in block direction */ }There’s some JavaScript for the full rotation and orientation:
// Bramus made a little helper for handling the requested animation frames import { trackProgress } from "https://esm.sh/@bramus/sda-utilities"; // Select the component const $model = document.QuerySelector("model-viewer"); // Animation begins with the first iteration const animation = $model.getAnimations()[0]; // Variable to get the animation's timing info let progress = animation.effect.getComputedTiming().progress * 1; // If when finished, $progress = 1 if (animation.playState === "finished") progress = 1; progress = Math.max(0.0, Math.min(1.0, progress)).toFixed(2); // Convert this to degrees $model.orientation = `0deg 0deg $(progress * -360)deg`;We’re using the effect to get the animation’s progress rather than the current timed spot. The current time value is always measured relative to the full range, so we need the effect to get the progress based on the applied animation.
Video Eight Scroll Velocity DetectionThe video description is helpful:
Bramus goes full experimental and uses Scroll-Driven Animations to detect the active scroll speed and the directionality of scroll. Detecting this allows you to style an element based on whether the user is scrolling (or not scrolling), the direction they are scrolling in, and the speed they are scrolling with … and this all using only CSS.
First off, this is a hack. What we’re looking at is expermental and not very performant. We want to detect the animations’s velocity and direction. We start with two custom properties.
@keyframes adjust-pos { from { --scroll-position: 0; --scroll-position-delayed: 0; } to { --scroll-position: 1; --scroll-position-delayed: 1; } } :root { animation: adjust-pos linear both; animation-timeline: scroll(root); }Let’s register those custom properties so we can interpolate the values:
@property --scroll-position { syntax: "<number>"; inherits: true; initial-value: 0; } @property --scroll-position-delayed { syntax: "<number>"; inherits: true; initial-value: 0; }As we scroll, those values change. If we add a little delay, then we can stagger things a bit:
:root { animation: adjust-pos linear both; animation-timeline: scroll(root); } body { transition: --scroll-position-delayed 0.15s linear; }The fact that we’re applying this to the body is part of the trick because it depends on the parent-child relationship between html and body. The parent element updates the values immediately while the child lags behind just a tad. The evaluate to the same value, but one is slower to start.
We can use the difference between the two values as they are staggered to get the velocity.
:root { animation: adjust-pos linear both; animation-timeline: scroll(root); } body { transition: --scroll-position-delayed 0.15s linear; --scroll-velocity: calc( var(--scroll-position) - var(--scroll-position-delayed) ); }Clever! If --scroll-velocity is equal to 0, then we know that the user is not scrolling because the two values are in sync. A positive number indicates the scroll direction is down, while a negative number indicates scrolling up,.
There’s a little discrepancy when scrolling abruptly changes direction. We can fix this by tighening the transition delay of --scroll-position-delayed but then we’re increasing the velocity. We might need a multiplier to further correct that… that’s why this is a hack. But now we have a way to sniff the scrolling speed and direction!
Here’s the hack using math functions:
body { transition: --scroll-position-delayed 0.15s linear; --scroll-velocity: calc( var(--scroll-position) - var(--scroll-position-delayed) ); --scroll-direction: sign(var(--scroll-velocity)); --scroll-speed: abs(var(--scroll-velocity)); }This is a little funny because I’m seeing that Chrome does not yet support sign() or abs(), at least at the time I’m watching this. Gotta enable chrome://flags. There’s a polyfill for the math brought to you by Ana Tudor right here on CSS-Tricks.
So, now we could theoretically do something like skew an element by a certain amount or give it a certain level of background color saturation depending on the scroll speed.
.box { transform: skew(calc(var(--scroll-velocity) * -25deg)); transition: background 0.15s ease; background: hsl( calc(0deg + (145deg * var(--scroll-direction))) 50 % 50% ); }We could do all this with style queries should we want to:
@container style(--scroll-direction: 0) { /* idle */ .slider-item { background: crimson; } } @container style(--scroll-direction: 1) { /* scrolling down */ .slider-item { background: forestgreen; } } @container style(--scroll-direction: -1) { /* scrolling down */ .slider-item { background: lightskyblue; } }Custom properties, scroll-driven animations, and style queries — all in one demo! These are wild times for CSS, tell ya what.
Video Nine OutroThe tenth and final video! Just a summary of the series, so no new notes here. But here’s a great demo to cap it off.
CodePen Embed Fallback Video TenUnleash the Power of Scroll-Driven Animations originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
Combining forces, GSAP & Webflow!
Change can certainly be scary whenever a beloved, independent software library becomes a part of a larger organization. I’m feeling a bit more excitement than concern this time around, though.
If you haven’t heard, GSAP (GreenSock Animation Platform) is teaming up with the visual website builder, Webflow. This mutually beneficial advancement not only brings GSAP’s powerful animation capabilities to Webflow’s graphical user interface but also provides the GSAP team the resources necessary to take development to the next level.
GSAP has been independent software for nearly 15 years (since the Flash and ActionScript days!) primarily supported by Club GSAP memberships, their paid tiers which offer even more tools and plugins to enhance GSAP further. GSAP is currently used on more than 12 million websites.
I chatted with Cassie Evans — GSAP’s Lead Bestower of Animation Superpowers and CSS-Tricks contributor — who confidently expressed that GSAP will remain available for the wider web.
It’s a big change, but we think it’s going to be a good one – more resources for the core library, more people maintaining the GSAP codebase, money for events and merch and community support, a VISUAL GUI in the pipeline.
The Webflow community has cause for celebration as well, as direct integration with GSAP has been a wishlist item for a while.
The webflow community is so lovely and creative and supportive and friendly too. It’s a good fit.
I’m so happy for Jack, Cassie, and Rodrigo, as well as super excited to see what happens next. If you don’t want to take my word for it, check out what Brody has to say about it.
Combining forces, GSAP & Webflow! originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
Mastering theme.json: You might not need CSS
I totally get the goal here: make CSS more modular and scalable in WordPress. Put all your global WordPress theme styles in a single file, including variations. JSON offers a nicely structured syntax that’s easily consumable by JavaScript, thereby allowing the sweet affordance of loading exactly what we want when we want it.
The problem, to me, is that writing “CSS” in a theme.json file is a complete mental model switcher-oo. Rather than selectors, we have a whole set of objects we have to know about just to select something. We have JSON properties that look and feel like CSS properties, only they have to be camelCased being JavaScript and all. And we’re configuring features in the middle of the styles, meaning we’ve lost a clear separation of concerns.
I’m playing devil’s advocate, of course. There’s a lot of upside to abstracting CSS with JSON for the very niche purpose of theming CMS templates and components. But after a decade of “CSS-in-JS is the Way™” I’m less inclined to buy into it. CSS is the bee’s knees just the way it is and I’m OK relying on it solely, whether it’s in the required style.css file or some other plain ol’ CSS file I generate. But that also means I’m losing out on the WordPress features that require you to write styles in a theme.json file, like style variations that can be toggled directly in the WordPress admin.
Regardless of all that, I’m linking this up because Justin does bang-up work (no surprise, really) explaining and illustrating the ways of CSS-in-WordPress. We have a complete guide that Ganesh rocked a couple of years ago. You might check that to get familiar with some terminology, jump into a nerdy deep dive on how WordPress generates classes from JSON, or just use the reference tables as a cheat sheet.
Mastering theme.json: You might not need CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
Solving Background Overflow With Inherited Border Radii
One of the interesting (but annoying) things about CSS is the background of children’s elements can bleed out of the border radius of the parent element. Here’s an example of a card with an inner element. If the inner element is given a background, it can bleed out of the card’s border.
CodePen Embed FallbackThe easiest way to resolve this problem is to add overflow: hidden to the card element. I’m sure that’s the go-to solution most of us reach for when this happens.
But doing this creates a new problem — content outside the card element gets clipped off — so you can’t use negative margins or position: absolute to shift the children’s content out of the card.
CodePen Embed FallbackThere is a slightly more tedious — but more effective — way to prevent a child’s background from bleeding out of the parent’s border-radius. And that is to add the same border-radius to the child element.
The easiest way to do this is allowing the child to inherit the parent’s border-radius:
.child { border-radius: inherit; } CodePen Embed FallbackIf the border-radius shorthand is too much, you can still inherit the radius for each of the four corners on a case-by-case basis:
.child { border-top-left-radius: inherit; border-top-right-radius: inherit; border-bottom-left-radius: inherit; border-bottom-right-radius: inherit; }Or, for those of you who’re willing to use logical properties, here’s the equivalent. (For an easier way to understand logical properties, replace top and left with start, and bottom and right with end.)
.child { border-start-start-radius: inherit; border-top-end-radius: inherit; border-end-start-radius: inherit; border-end-end-radius: inherit; } Can’t we just apply a background on the card?If you have a background directly on the .card that contains the border-radius, you will achieve the same effect. So, why not?
CodePen Embed FallbackWell, sometimes you can’t do that. One situation is when you have a .card that’s split into two, and only one part is colored in.
CodePen Embed Fallback So, why should we do this?Peace of mind is probably the best reason. At the very least, you know you won’t be creating problems down the road with the radius manipulation solution.
This pattern is going to be especially helpful when CSS Anchor Positioning gains full support. I expect that would become the norm popover positioning soon in about 1-2 years.
That said, for popovers, I personally prefer to move the popover content out of the document flow and into the <body> element as a direct descendant. By doing this, I prevent overflow: hidden from cutting off any of my popovers when I use anchor positioning.
Solving Background Overflow With Inherited Border Radii originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
Close, Exit, Cancel: How to End User Interactions Well
What’s in a word? Actions. In the realm of user interfaces, a word is construed as the telltale of a control’s action. Sometimes it points us in the correct direction, and sometimes it leads us astray. We talk a lot about semantics in front-end web development, but outside of code, semantics are at the heart of copywriting where each word we convey can mean different things to different people. Words, if done right, add clarity and direction.
As a web user, I’ve come across words in user interfaces that have misled me. And not necessarily by design, either. Some words are synonymous with others and their true meaning depends entirely on context. Some words are easy to mistake for an unintended meaning because they are packed with so much meaning. A word might belong to a fellowship of interchangeable words.
Although I’m quite riled up when I misread content on a page — upset at the lack of clarity more than anything — as a developer, I can’t say I’ve always chosen the best possible words or combination of words for all the user interfaces I’ve ever made. But experience, both as a user and a developer, has elevated my commonsense when it comes to some of the literary choices I make while coding.
This article covers the words I choose for endings, to help users move away, and move on, without any confusion from the current process they are at on the screen. I went down this rabbit hole because I often find that ending something can mean many things — whether it be canceling an action, quitting an application, closing an element, navigating back, exiting a chat interaction… You get the idea. There are many ways to say that something is done, complete, and ready to move on to something else. I want to add clarity to that.
Getting CanceledIf there’s a Hall of Fame for button labels, this is the Babe Ruth of them all. “Cancel” is a widely used word to indicate an action that ends something. Cancel is a sharp, tenacious action. The person wants to bail on some process that didn’t go the way they expected it to. Maybe the page reveals a form that the person didn’t realize would be so long, so they want to back off. It could be something you have no control over whatsoever, like that person realizing they do not have their credit card information handy during checkout and they have to come back another time.
Cancel can feel personal at times, right? Don’t like the shipping costs calculated at checkout? Cancel the payment. Don’t like the newsletter? Cancel The Subscription. But really, the person only wants to undo an incorrect action or decision leaving no trace of it behind in favor of a clean slate to try again… or not.
The only times I feel betrayed by the word cancel is when the process I’m trying to end continues anyway. That comes up most when submitting forms with incorrect information. I enter something inadvertently, hit a big red Cancel button, yet the information I’ve “saved” persists to the extent that I either need to contact customer support or start looking for alternatives.
That’s the bottom line: Use “cancel” as an opportunity to confirm. It’s the person telling you, “Hey, that’s not actually what I meant to do,” and you get to step in and be the hero to wipe the mistake clean and set things up for a second chance. We’re not technically “ending” anything but rather starting clean and picking things back up for a better go. Think about that the next time you find yourself needing a label that encourages the user to try again. You might even consider synonyms that are less closely associated with closed endings, such as reset or retry.
Quitting or Exiting?Quit window, quit tab, quit app — now we’re talking about finality. When we “quit” or “exit” something, we’re changing course. We’ve made progress in one direction and decide it’s time to chart a different path. If we’re thinking about it in terms of freeway traffic, you might say that “quitting” is akin to pulling over and killing the engine, and “exiting” is taking leaving the freeway for another road. There’s a difference, although the two terms are closely related.
As far as we’re concerned as developers, quit and exit are hard stop points in an application. It’s been put to rest. Nothing else beyond this should be possible except its rebirth when the service is restarted or reopened. So, if your page is capable of nuking the current experience and the user takes it, then quit is the better label to make that point. We’re quitting and have no plans to restart or re-engage. If you were to “quit” your job, it’s not like your employer is expecting you to report for duty on Monday… or any other day for that matter.
But here’s my general advice about the word quit: only use it if you have to. I see very few use cases where we actually want to offer someone a true way to quit something. It’s so effective at conveying finality in web interfaces that it shuts the door on any future actions. For instance, I find that cancel often works in its place. And, personally, I find that saying “cancel payment” is more widely applicable. It’s softer and less rigid in the sense that it leaves the possibility to resume a process down the road.
Quit is also a simple process. Just clear everything and be gone. But if quitting means the user might lose some valuable data or progress, then that’s something they have to be warned about. In that case, exit and save may be better guidance.
I consider Exit the gentler twin of Quit. I prefer Quit just for the ultimatum of it. I see Exit used less frequently in interfaces than I see Quit. In rare cases, I might see Exit used specifically because of its softer nature to Quit even though “quitting” is the correct semantic choice given that the user really wants to wipe things clean and the assurance that nothing is left behind. Sometimes a “tougher” term is more reassuring.
Exit, however, is an excellent choice for actions that represent the end of human-to-human interactions — things like Exit Group, Exit Chat, Exit Streaming, Exit Class. If this person is kindly saying goodbye to someone or something but open to future interactions, allow them to exit when they’re done. They’re not quitting anything and we aren’t shoving them out the door.
Going Back (and Forth)Let’s talk about navigation. That’s the way we describe moving around the internet. We navigate from one place to another, to another, to another, and so on. It’s a journey of putting one digital foot in front of the other on the way to somewhere. That journey comes to an end when we get to our destination… or when we “quit” or “exit” the journey as we discussed above.
But the journey may take twists and turns. Not all movement is linear on the web. That’s why we often leave breadcrumbs in interfaces, right? It’s wayfinding on the web and provides people with a way to go “back” where they came from. Maybe that person forgot a step and needs to head back in order to move forward again.
In other words, back displaces people — laterally and hierarchically. Laterally, back (and its synonym, previous), backtracks across the same level in a process, for instance, between two sections of the same form, or two pages of the same document. Hierarchically, back — not to mention more explicit variants like “home” — is a level above that in the navigation hierarchy.
I like the explicit nature of saying something like “Home” when it comes to navigating someone “back” to a location or state. There’s no ambiguity there: hey, let’s go back home. Being explicit opens you up to more verbose labels but brevity isn’t always the goal. Even in iconography, adding more detail to a visual can help add clarity. The same is true with content in user interfaces. My favorite example is the classic “Back to Top” button on many pages that navigate you to the “top” of the page. We’re going “back to the top” which would not have been clear if we had used “Back” alone. Back where? That’s an important question — particularly when working with in-page anchors — and the answer may not be as obvious to others as it is to you. Communicating that level of hierarchy explicitly is a navigational feature.
While the “Back to Top” example I gave is a better illustration of lateral displacement than hierarchical displacement, I tend to avoid the label back with any sort of lateral navigation because moving laterally typically involves navigating between states more than navigating between pages. For example, the user may be navigating from a “logged in” state to a “logged out” state. In this case, I prefer being even more explicit — e.g., Save and Go Back, or Cancel and Go Home — than hierarchical navigation because we’re changing states on top of moving away from something.
Closing DownClose is yet another term you’ll find in the wild for conveying the “end” of something. It’s quite similar to Back in the sense that it serves dual purposes. It can be for navigation — close the current page and go back — or it can be for canceling an action — close the current page, and either discard or save all the data entered so far.
I prefer Close for neither of those cases. If we’re in the context of navigation, I like the clarity of the more explicit guidance we discussed above, e.g., Go Back, Previous, or Go Home. Giving someone an instruction to Close doesn’t say where that person is going to land once navigating away from the current page. And if we’re dealing with actions, Save and Close affirms the person that their data will be saved, rather than simply “closing” it out. If we were to simply say “cancel” instead, the insinuation is that the user is quitting the action and can expect to lose their work.
The one time I do feel that “Close” is the ideal label is working with pop-up dialogues and modals. Placing “Close” at the top-right (or the block-start, inline-end edge if we’re talking logical directions) corner is more than clear enough about what happens to the pop-up or modal when clicking it. We can afford to be a little less explicit with our semantics when someone’s focus is trapped in a specific context.
The End.I’ve saved the best for last, right? There’s no better way to connote an ending than simply calling it the “end”. It works well when we pair it with what’s ending.
End Chat. End Stream. End Webinar.
You’re terminating an established connection, not with a process, but with a human. And this is not some abrupt termination like Quit or Cancel. It’s more of a proper goodbye. Consider it also a synonym to Exit because the person ending the interaction may simply be taking a break. They’re not necessarily quitting something for good. Let’s leave the light on the front patio for them to return later and pick things back up..
And speaking of end, we’ve reached the end of this article. That’s the tricky, but liberating, thing about content semantics — some words may technically be correct but still mislead site visitors. It’s not that we’re ever trying to give someone bad directions, but it can still happen because this is a world where there are many ways of saying the same thing. Our goal is to be unambiguous and the milestone is clarity. Settling on the right word or combination of words takes effort. Anyone who has struggled with naming things in code knows about this. It’s the same for naming things outside of code.
I did not make an attempt to cover each and every word or way to convey endings. The point is that our words matter and we have all the choice and freedom in the world to find the best fit. But maybe you’ve recently run into a situation where you needed to “end” something and communicate that in an interface. Did you rely on something definitive and permanent (e.g. quit) or did you find that softer language (e.g. exit) was the better direction? What other synonyms did you consider? I’d love to know!
End Article.
Close, Exit, Cancel: How to End User Interactions Well originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
CSS Tricks That Use Only One Gradient
CSS gradients have been so long that there’s no need to rehash what they are and how to use them. You have surely encountered them at some point in your front-end journey, and if you follow me, you also know that I use them all the time. I use them for CSS patterns, nice CSS decorations, and even CSS loaders. But even so, gradients have a tough syntax that can get very complicated very quickly if you’re not paying attention.
In this article, we are not going to make complex stuff with CSS gradients. Instead, we’re keeping things simple and I am going to walk through all of the incredible things we can do with just one gradient.
Only one gradient? In this case, reading the doc should be enough, no?
No, not really. Follow along and you will see that gradients are easy at their most basic, but are super powerful if we push them — or in this case, just one — to their limits.
CSS patternsOne of the first things you learn with gradients is that we can establish repeatable patterns with them. You’ve probably seen some examples of checkerboard patterns in the wild. That’s something we can quickly pull off with a single CSS gradient. In this case, we can reach for the repeating-conic-gradient() function:
background: repeating-conic-gradient(#000 0 25%, #fff 0 50%) 0 / 100px 100px;A more verbose version of that without the background shorthand:
background-image: repeating-conic-gradient(#000 0 25%, #fff 0 50%); background-size: 100px 100px;Either way, the result is the same:
CodePen Embed FallbackPretty simple so far, right? You have two colors that you can easily swap out for other colors, plus the background-size property to control the square shapes.
If we change the color stops — where one color stops and another starts — we get another cool pattern based on triangles:
background: repeating-conic-gradient(#000 0 12.5%, #fff 0 25%) 0 / 100px 100px; CodePen Embed FallbackIf you compare the CSS for the two demos we’ve seen so far, you’ll see that all I did was divide the color stops in half, 25% to 12.5% and 50% to 25%.
Another one? Let’s go!
CodePen Embed FallbackThis time I’m working with CSS variables. I like this because variables make it infinitely easier to configure the gradients by updating a few values without actually touching the syntax. The calculation is a little more complex this time around, as it relies on trigonometric functions to get accurate values.
I know what you are thinking: Trigonometry? That sounds hard. That is certainly true, particularly if you’re new to CSS gradients. A good way to visualize the pattern is to disable the repetition using the no-repeat value. This isolates the pattern to one instance so that you clearly see what’s getting repeated. The following example declares background-image without a background-size so you can see the tile that repeats and better understand each gradient:
CodePen Embed FallbackI want to avoid a step-by-step tutorial for each and every example we’re covering so that I can share lots more examples without getting lost in the weeds. Instead, I’ll point you to three articles you can refer to that get into those weeds and allow you to pick apart our examples.
- How to create background patterns using CSS & conic-gradient (Verpex blog)
- Learn CSS radial-gradient by Building Background Patterns (freeCodeCamp)
- Background Patterns, Simplified by Conic Gradients (Ana Tudor)
I’ll also encourage you to open my online collection of patterns for even more examples. Most of the examples are made with multiple gradients, but there are plenty that use only one. The goal of this article is to learn a few “single gradient” tricks — but the ultimate goal is to be able to combine as many gradients as possible to create cool stuff!
Grid linesLet’s start with the following example:
CodePen Embed FallbackYou might claim that this belongs under “Patterns” — and you are right! But let’s make it more flexible by adding variables for controlling the thickness and the total number of cells. In other words, let’s create a grid!
.grid-lines { --n: 3; /* number of rows */ --m: 5; /* number of columns */ --s: 80px; /* control the size of the grid */ --t: 2px; /* the thickness */ width: calc(var(--m)*var(--s) + var(--t)); height: calc(var(--n)*var(--s) + var(--t)); background: conic-gradient(from 90deg at var(--t) var(--t), #0000 25%, #000 0) 0 0/var(--s) var(--s); }First of all, let’s isolate the gradient to better understand the repetition (like we did in the previous section).
CodePen Embed FallbackOne repetition will give us a horizontal and a vertical line. The size of the gradient is controlled by the variable --s, so we define the width and height as a multiplier to get as many lines as we want to establish the grid pattern.
What’s with “+ var(--t)” in the equation?
The grid winds up like this without it:
CodePen Embed FallbackWe are missing lines at the right and the bottom which is logical considering the gradient we are using. To fix this, the gradient needs to be repeated one more time, but not at full size. For this reason, we are adding the thickness to the equation to have enough space for the extra repetition and the get the missing lines.
CodePen Embed FallbackAnd what about a responsive configuration where the number of columns depends on the available space? We remove the --m variable and define the width like this:
width: calc(round(down, 100%, var(--s)) + var(--t));Instead of multiplying things, we use the round() function to tell the browser to make the element full width and round the value to be a multiple of --s. In other words, the browser will find the multiplier for us!
Resize the below and see how the grid behaves:
CodePen Embed FallbackIn the future, we will also be able to do this with the calc-size() function:
width: calc-size(auto, round(down, size, var(--s)) + var(--t));Using calc-size() is essentially the same as the last example, but instead of using 100% we consider auto to be the width value. It’s still early to adopt such syntax. You can test the result in the latest version of Chrome at the time of this writing:
CodePen Embed Fallback Dashed linesLet’s try something different: vertical (or horizontal) dashed lines where we can control everything.
.dashed-lines { --t: 2px; /* thickness of the lines */ --g: 50px; /* gap between lines */ --s: 12px; /* size of the dashes */ background: conic-gradient(at var(--t) 50%, #0000 75%, #000 0) var(--g)/calc(var(--g) + var(--t)) var(--s); } CodePen Embed FallbackCan you figure out how it works? Here is a figure with hints:
Try creating the horizontal version on your own. Here’s a demo that shows how I tackled it, but give it a try before peeking at it.
What about a grid with dashed lines — is that possible?
Yes, but using two gradients instead of one. The code is published over at my collection of CSS shapes. And yes, the responsive behavior is there as well!
CodePen Embed Fallback Rainbow gradientHow would you create the following gradient in CSS?
You might start by picking as many color values along the rainbow as you can, then chaining them in a linear-gradient:
linear-gradient(90deg, red, yellow, green, /* etc. */, red);Good idea, but it won’t get you all the way there. Plus, it requires you to juggle color stops and fuss with them until you get things just right.
There is a simpler solution. We can accomplish this with just one color!
background: linear-gradient(90deg in hsl longer hue, red 0 0);I know, the syntax looks strange if you’re seeing the new color interpolation for the first time.
If I only declare this:
background: linear-gradient(90deg, red, red); /* or (90deg, red 0 0) */…the browser creates a gradient that goes from red to red… red everywhere! When we set this “in hsl“, we’re changing the color space used for the interpolation between the colors:
background: linear-gradient(90deg in hsl, red, red);Now, the browser will create a gradient that goes from red to red… this time using the HSL color space rather than the default RGB color space. Nothing changes visually… still see red everywhere.
The longer hue bit is what’s interesting. When we’re in the HSL color space, the hue channel’s value is an angle unit (e.g., 25deg). You can see the HSL color space as a circle where the angle defines the position of the color within that circle.
Since it’s a circle, we can move between two points using a “short” path or “long” path.
If we consider the same point (red in our case) it means that the “short” path contains only red and the “long” path runs into all the colors as it traverses the color space.
CodePen Embed FallbackAdam Argyle published a very detailed guide on high-definition colors in CSS. I recommend reading it because you will find all the features we’re covering (this section in particular) to get more context on how everything comes together.
We can use the same technique to create a color wheel using a conic-gradient:
background: conic-gradient(in hsl longer hue,red 0 0); CodePen Embed FallbackAnd while we are on the topic of CSS colors, I shared another fun trick that allows you to define an array of color values… yes, in CSS! And it only uses a single gradient as well.
Hover effectsLet’s do another exercise, this time working with hover effects. We tend to rely on pseudo-elements and extra elements when it comes to things like applying underlines and overlays on hover, and we tend to forget that gradients are equally, if not more, effective for getting the job done.
Case in point. Let’s use a single gradient to form an underline that slides on hover:
h3 { background: linear-gradient(#1095c1 0 0) no-repeat var(--p,0) 100%/var(--p, 0) .1em; transition: 0.4s, background-position 0s; } h3:hover { --p: 100%; } CodePen Embed FallbackYou likely would have used a pseudo-element for this, right? I think that’s probably how most people would approach it. It’s a viable solution but I find that using a gradient instead results in cleaner, more concise CSS.
You might be interested in another article I wrote for CSS-Tricks where I use the same technique to create a wide variety of cool hover effects.
CSS shapesCreating shapes with gradients is my favorite thing to do in CSS. I’ve been doing it for what feels like forever and love it so much that I published a “Modern Guide for Making CSS Shapes” over at Smashing Magazine earlier this year. I hope you check it out not only to learn more tricks but to see just how many shapes we can create with such a small amount of code — many that rely only on a single CSS gradient.
Some of my favorites include zig-zag borders:
CodePen Embed Fallback…and “scooped” corners:
CodePen Embed Fallback…as well as sparkles:
CodePen Embed Fallback…and common icons like the plus sign:
CodePen Embed FallbackI won’t get into the details of creating these shapes to avoid making this article long and boring. Read the guide and visit my CSS Shape collection and you’ll have everything you need to make these, and more!
Border image tricksLet’s do one more before we put a cap on this. Earlier this year, I discovered how awesome the CSS border-image property is for creating different kinds of decorations and shapes. And guess what? border-image limits us to using just one gradient, so we are obliged to follow that restriction.
Again, just one gradient and we get a bunch of fun results. I’ll drop in my favorites like I did in the last section. Starting with a gradient overlay:
CodePen Embed FallbackWe can use this technique for a full-width background:
CodePen Embed Fallback…as well as heading dividers:
CodePen Embed Fallback…and even ribbons:
CodePen Embed FallbackAll of these have traditionally required hacks, magic numbers, and other workarounds. It’s awesome to see modern CSS making things more effortless. Go read my article on this topic to find all the interesting stuff you can make using border-image.
Wrapping upI hope you enjoyed this collection of “single-gradient” tricks. Most folks I know tend to use gradients to create, well, gradients. But as we’ve seen, they are more powerful and can be used for lots of other things, like drawing shapes.
I like to add a reminder at the end of an article like this that the goal is not to restrict yourself to using one gradient. You can use more! The goal is to get a better handle on how gradients work and push them in interesting ways — that, in turn, makes us better at writing CSS. So, go forth and experiment — I’d love to see what you make!
CSS Tricks That Use Only One Gradient originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
WPGraphQL Becomes a Canonical Plugin: My Move to Automattic
It’s always a gas when a good person doing good work gets a good deal. In this case, Jason’s viral WPGraphQL plugin has not only become a canonical WordPress plugin, but creator Jason Bahl is joining Automattic as well.
I’m linking this up because it’s notable for a few reasons:
- WPGraphQL is a must-have plugin for creating headless WordPress sites and making it a canonical plugin is WordPress making a big step in that direction.
- Jason is leaving WP Engine to join Automattic and we all know what a dumpster fire that relationship has become. (WP Engine also has a big foot in headless WordPress.)
- You might be hearing about canonical plugins for the first time.
Congrats, Jason! I didn’t know you were in Denver — maybe we’ll bump into each other and I can give you a well-deserved high-five. ✋
WPGraphQL Becomes a Canonical Plugin: My Move to Automattic originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
2024: More CSS At-Rules Than the Past Decade Combined
More times than I can count, while writing, I get myself into random but interesting topics with little relation to the original post. In the end, I have to make the simple but painful choice of deleting or archiving hours of research and writing because I know most people click on a post with a certain expectation of what they’ll get, and I know it isn’t me bombing them with unrelated rants about CSS.
This happened to me while working on Monday’s article about at-rules. All I did there was focus on a number of recipes to test browser support for CSS at-rules. In the process, I began to realize, geez we have so many new at-rules — I wonder how many of them are from this year alone. That’s the rabbit hole I found myself in once I wrapped up the article I was working on.
And guess what, my hunch was right: 2024 has brought more at-rules than an entire decade of CSS.
It all started when I asked myself why we got a selector() wrapper function for the @supports at-rule but are still waiting for an at-rule() version. I can’t pinpoint the exact reasoning there, but I’m certain there wasn’t much of a need to check the support of at-rules because, well, there weren’t that many of them — it’s just recently that we got a windfall of at-rules.
Some historical contextSo, right around 1998 when the CSS 2 recommendation was released, @import and @page were the only at-rules that made it into the CSS spec. That’s pretty much how things remained until the CSS 2.1 recommendation in 2011 introduced @media. Of course, there were other at-rules like — @font-face, @namespace and @keyframes to name a few — that had already debuted in their own respective modules. By this time, CSS dropped semantic versioning, and the specification didn’t give a true picture of the whole, but rather individual modules organized by feature.
Random tangent: The last accepted consensus says we are at “CSS 3”, but that was a decade ago and some even say we should start getting into CSS 5. Wherever we are is beside the point, although it’s certainly a topic of discussion happening. Is it even useful to have a named version?
The @supports at-rule was released in 2011 in CSS Conditional Rules Module Level 3 — Levels 1 and 2 don’t formally exist but refer to the original CSS 1 and 2 recommendations. We didn’t actually get support for it in most browsers until 2015, and at that time, the existing at-rules already had widespread support. The @supports was only geared towards new properties and values, designed to test browser support for CSS features before attempting to apply styles.
The numbersAs of today, we have a grand total of 18 at-rules in CSS that are supported by at least one major browser. If we look at the year each at-rule was initially defined in a CSSWG Working Draft, we can see they all have been published at a fairly consistent rate:
If we check the number of at-rules supported on each browser per year, however, we can see the massive difference in browser activity:
If we just focus on the last year a major browser shipped each at-rule, we will notice that 2024 has brought us a whopping seven at-rules to date!
Data collected from caniuse.I like little thought experiments like this. Something you’re researching leads to researching about the same topic; out of scope, but tangentially related. It may not be the sort of thing you bookmark and reference daily, but it is good cocktail chatter. If nothing else, it’s affirming the feeling that CSS is moving fast, like really fast in a way we haven’t seen since CSS 3 first landed.
It also adds context for the CSS features we have — and don’t have. There was no at-rule() function initially because there weren’t many at-rules to begin with. Now that we’ve exploded with more new at-rules than the past decade combined, it may be no coincidence that just last week the Chrome Team updated the function’s status from New to Assigned!
One last note: the reason I’m even thinking about at-rules at all is that we’ve updated the CSS Almanac, expanding it to include more CSS features including at-rules. I’m trying to fill it up and you can always help by becoming a guest writer.
2024: More CSS At-Rules Than the Past Decade Combined originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
Smashing Hour With Heydon Pickering
I sat down with Heydon Pickering in the most recent episode of the Smashing Hour. Full transparency: I was nervous as heck. I’ve admired Heydon’s work for years, and even though we run in similar circles, this was our first time meeting. You know how you build some things up in your mind and sorta psyche yourself out? Yeah, that.
Heydon is nothing short of a gentleman and, I’ll be darned, easy to talk to. As is the case with any Smashing Hour, there’s no script, no agenda, no nothing. We find ourselves getting into the weeds of accessibility testing and documentation — or the lack of it — before sliding into the stuff he’s really interested in and excited about today: styling sound. Dude pulled out a demo and walked me (and everyone else) through the basics of the Web Audio API and how he’s using it to visualize sounds in tons of groovy ways that I now want hooked up to my turntable somehow.
Smashing Hour With Heydon Pickering originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
Smashing Conf: Is Atomic Design Dead?
In his Is Atomic Design Dead? presentation at Smashing Conf New York, Brad Frost discussed the history of design systems and today's situation especially in light of very capable AI models than can generate code and designs. Here's my notes on his talk.
- Websites started as HTML and CSS. People began to design websites in Photoshop and as the number of Web sites and apps increased, the need for managing a brand and style across multiple platforms became clear. To manage this people turned to frameworks and component libraries which resulted in more frameworks and tools that eventually got integrated into design tools like Figma. It's been an ongoing expansion...
- There's been lots of change over the years but at the highest level, we have design systems and products that use them to enforce brand, consistency, accessibility, and more.
- Compliance to design systems pushes from one side and product needs push from the other. There needs to be a balance but currently the gap between the two is growing. A good balance is achieved through a virtuous cycle between product and systems.
- The atomic design system tried to intentionally define use of atoms, molecules, organisms, templates, and pages to bridge the gap between the end state of a product and a design system.
- As an industry, we went too far in resourcing design systems and making them a standalone thing within a company. They've been isolated.
- Design system makers can't be insular. They need to reach out to product teams and work with them. They need to be helping product teams achieve their goals.
- What if there were one global design system with common reusable components? Isn't that what HTML is for? Yes, but it's insufficient because we're still rebuilding date pickers everywhere.
- Open UI tracks popular design systems and what's in them. It's a start to seeing what global component needs for the Web could look like.
- Many pattern libraries ship with an aesthetic and people need to tweak it. A global design system should be very vanilla so you can style it as much as you want.
- The Web still has an amazing scale of communication and collaboration. We need to rekindle the ideas of the early Web. We need to share and build together to get to a common freely usable design system.
- AI models can help facilitate design system work. Today they do an OK job but in the future, fine-tuned models may create custom components on the fly. They can also translate between one design system and another or translate across programming languages.
- This methodology could help companies translate existing and legacy code to new modern design systems. Likewise sketches or mockups could be quickly translated directly to design system components thereby speeding up processes.
- Combining design system specifications with large language models allows you to steer AI generations more directly toward the right kind of code and components.
- When product experiences are more dynamic (can be built on the fly), can we adapt them to individual preferences and needs? Like custom styles or interactions.
- AI is now part of our design system toolkit and design systems are part of our AI toolkit.
- But the rapid onset of AI also raises higher level questions about what designers and developers should be doing in the future? We're more than rectangle creators. We think and feel which differentiates us from just production level tasks. Use your brains, your intuition, and whole self to solve real problems.
Smashing Conf: How to Use AI to Build Accessible Products
In her How to Use AI to Build Accessible Products presentation at Smashing Conf New York, Carie Fisher discussed using AI coding tools to test and suggest fixes for accessibility issues in Web pages. Here's my notes on her talk.
- AI is everywhere. You can use it to write content, code, create images, and more. It impacts how everyone will work.
- But ultimately, AI is just a tool but it might not always be the right one. We need to find the tasks where it has the potential to add value.
- Over 1 billion people on the planet identify as having a disability. Accessible code allows them to access digital experiences and helps companies be complaint with emerging laws requiring accessible Web pages and apps. Businesses also get SEO, brand, and more benefits from accessible code.
- AI tools like Github Copilot can find accessibility issues in seconds consistently, especially compared to the manual checks currently being done by humans. AI can also spot patterns across a codebase and suggest solutions.
- Existing AI coding tools like Github Copilot are already better than Linters for finding accessibility issues.
- AI can suggest and implement code fixes for accessibility issues. It can also be added to CI/CD pipelines to check for accessibility issues at the point of each commit. AI can also serve as an accessibility mentor for developers by providing real-time suggestions.
- More complex accessibility issues especially those that need user context may go unfound when just using AI. Sometimes AI output can be incomplete or hallucinate solutions that are not correct. As a result, we can't over rely on just AI to solve all accessibility problems. We still need human review today.
- To improve AI accessibility, provide expanded prompts that reference or include specifications. Code reviews can double check accessibility suggestions from AI-based systems. Regularly test and refine your AI-based solutions to improve outcomes.
- Combing AI and human processes and values can help build a culture of accessibility.
Searching for a New CSS Logo
There is an amazing community effort happening in search of a new logo for CSS. I was a bit skeptical at first, as I never really considered CSS a “brand.” Why does it need a logo? For starters, the current logo seems… a bit dated.
Displayed quite prominently is the number 3. As in CSS version 3, or simply CSS3. Depending on your IDE’s selected icon pack of choice, CSS file icons are often only the number 3.
To give an incredibly glossed-over history of CSS3:
- Earliest draft specification was in 1999!
- Adoption began in 2011, when it was published as the W3C Recommendation.
- It’s been used ever since? That can’t be right…
CSS is certainly not stuck in 2011. Take a look at all the features added to CSS in the past five years (warning, scrolling animation ahead):
CodePen Embed Fallback(Courtesy of Alex Riviere)
Seems like this stems mainly from the discontinuation of version numbering for CSS. These days, we mostly reference newer CSS features by their individual specification level, such as Selectors Level 4 being the current Selectors specification, for example.
A far more general observation on the “progress” of CSS could be taking a look at features being implemented — things like Caniuse and Baseline are great for seeing when certain browsers implemented certain features. Similarly, the Interop Project is a group consisting of browsers figuring out what to implement next.
There are ongoing discussions about the “eras” of CSS, though, and how those may be a way of framing the way we refer to CSS features.
Chris posted about CSS4 here on CSS-Tricks (five years ago!), discussing how successful CSS3 was from a marketing perspective. Jen Simmons also started a discussion back in 2020 on the CSS Working Group’s GitHub about defining CSS4. Knowing that, are you at least somewhat surprised that we have blown right by CSS4 and are technically using CSS5?
The CSS-Next Community Group is leading the charge here, something that member Brecht de Ruyte introduced earlier this year at Smashing Magazine. The purpose of this group is to, well, determine what’s next for CSS! The group defines the CSS versions as:
- CSS3 (~2009-2012): Level 3 CSS specs as defined by the CSSWG
- CSS4 (~2013-2018): Essential features that were not part of CSS3, but are already a fundamental part of CSS.
- CSS5 (~2019-2024): Newer features whose adoption is steadily growing.
- CSS6 (~2025+): Early-stage features that are planned for future CSS.
Check out this slide deck from November 2023 detailing the need for defining stronger versioning. Their goals are clear in my opinion:
- Help developers learn CSS.
- Help educators teach CSS.
- Help employers define modern web skil…
- Help the community understand the progression of CSS capabilities over time.
Circling back around to the logo, I have to agree: Yes, it’s time for a change.
Back in August, Adam Argyle opened an issue on the CSS-Next project on GitHub to drum up ideas. The thread is active and ongoing, though appears to be honing in on a release candidate. Let’s take a look at some proposals!
Nils Binder, from 9elements, proposed this lovely design, riffing on the “cascade.” Note the river-like “S” shape flowing through the design.
Chris Kirk-Nielson pitched a neat interactive logo concept he put together a while back. The suggestion plays into the “CSS is Awesome” meme, where the content overflows the wrapper. While playful and recognizable, Nils raised an excellent point:
Regarding the reference to the ‘CSS IS AWESOME’ meme, I initially chuckled, of course. However, at the same time, the meme also represents CSS as something quirky, unpredictable, and full of bugs. I’m not sure if that’s the exact message that needs to be repeated in the logo. It feels like it reinforces the recurring ‘CSS is broken’ mantra. To exaggerate: CSS is subordinate to JS and somehow broken.
Wow, is this the end of an era for the familiar meme?
It’s looking that way, as the current candidate builds off of Javi Aguilar’s proposal. Javi’s design is being iterated upon by the group, it’s shaping up and looks great hanging with friends:
Javi describes the design considerations in the thread. Personally, I’m a fan of the color choice, and the softer shape differentiates it from the more rigid JavaScript and Typescript logos.
As mentioned, the discussion is ongoing and the design is actively being worked on. You can check out the latest versions in Adam’s CodePen demo:
Or if checking out design files is more your speed, take a look in Figma.
CodePen Embed FallbackI think the thing that impresses me most about community initiatives like this is the collaboration involved. If you have opinions on the design of the logo, feel free to chime in on the discussion thread!
Once the versions are defined and the logo finalized, the only thing left to decide on will be a mascot for CSS. A chameleon? A peacock? I’m sure the community will choose wisely.
Searching for a New CSS Logo originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
New business wanted
Last week Krijn and I decided to cancel performance.now() 2021. Although it was the right decision it leaves me in financially fairly dire straits. So I’m looking for new jobs and/or donations.
Even though the Corona trends in NL look good, and we could probably have brought 350 people together in November, we cannot be certain: there might be a new flare-up. More serious is the fact that it’s very hard to figure out how to apply the Corona checks Dutch government requires, especially for non-EU citizens. We couldn’t figure out how UK and US people should be tested, and for us that was the straw that broke the camel’s back. Cancelling the conference relieved us of a lot of stress.
Still, it also relieved me of a lot of money. This is the fourth conference in a row we cannot run, and I have burned through all my reserves. That’s why I thought I’d ask for help.
So ...
Has QuirksMode.org ever saved you a lot of time on a project? Did it advance your career? If so, now would be a great time to make a donation to show your appreciation.
I am trying my hand at CSS coaching. Though I had only few clients so far I found that I like it and would like to do it more. As an added bonus, because I’m still writing my CSS for JavaScripters book I currently have most of the CSS layout modules in my head and can explain them straight away — even stacking contexts.
Or if there’s any job you know of that requires a technical documentation writer with a solid knowledge of web technologies and the browser market, drop me a line. I’m interested.
Anyway, thanks for listening.
position: sticky, draft 1
I’m writing the position: sticky part of my book, and since I never worked with sticky before I’m not totally sure if what I’m saying is correct.
This is made worse by the fact that there are no very clear tutorials on sticky. That’s partly because it works pretty intuitively in most cases, and partly because the details can be complicated.
So here’s my draft 1 of position: sticky. There will be something wrong with it; please correct me where needed.
The inset properties are top, right, bottom and left. (I already introduced this terminology earlier in the chapter.)
h3,h4,pre {clear: left} section.scroll-container { border: 1px solid black; width: 300px; height: 250px; padding: 1em; overflow: auto; --text: 'scroll box'; float: left; clear: left; margin-right: 0.5em; margin-bottom: 1em; position: relative; font-size: 1.3rem; } .container,.outer-container { border: 1px solid black; padding: 1em; position: relative; --text: 'container'; } .outer-container { --text: 'outer container'; } :is(.scroll-container,.container,.outer-container):before { position: absolute; content: var(--text); top: 0.2em; left: 0.2em; font-size: 0.8rem; } section.scroll-container h2 { position: sticky; top: 0; background: white; margin: 0 !important; color: inherit !important; padding: 0.5em !important; border: 1px solid; font-size: 1.4rem !important; } .nowrap p { white-space: nowrap; } Introductionposition: sticky is a mix of relative and fixed. A sticky box takes its normal position in the flow, as if it had position: relative, but if that position scrolls out of view the sticky box remains in a position defined by its inset properties, as if it has position: fixed. A sticky box never escapes its container, though. If the container start or end scrolls past the sticky box abandons its fixed position and sticks to the top or the bottom of its container.
It is typically used to make sure that headers remain in view no matter how the user scrolls. It is also useful for tables on narrow screens: you can keep headers or the leftmost table cells in view while the user scrolls.
Scroll box and containerA sticky box needs a scroll box: a box that is able to scroll. By default this is the browser window — or, more correctly, the layout viewport — but you can define another scroll box by setting overflow on the desired element. The sticky box takes the first ancestor that could scroll as its scroll box and calculates all its coordinates relative to it.
A sticky box needs at least one inset property. These properties contain vital instructions, and if the sticky box doesn’t receive them it doesn’t know what to do.
A sticky box may also have a container: a regular HTML element that contains the sticky box. The sticky box will never be positioned outside this container, which thus serves as a constraint.
The first example shows this set-up. The sticky <h2> is in a perfectly normal <div>, its container, and that container is in a <section> that is the scroll box because it has overflow: auto. The sticky box has an inset property to provide instructions. The relevant styles are:
section.scroll-container { border: 1px solid black; width: 300px; height: 300px; overflow: auto; padding: 1em; } div.container { border: 1px solid black; padding: 1em; } section.scroll-container h2 { position: sticky; top: 0; } The rules Sticky headerRegular content
Regular content
Regular content
Regular content
Regular content
Regular content
Regular content
Content outside container
Content outside container
Content outside container
Content outside container
Content outside container
Content outside container
Now let’s see exactly what’s going on.
A sticky box never escapes its containing box. If it cannot obey the rules that follow without escaping from its container, it instead remains at the edge. Scroll down until the container disappears to see this in action.
A sticky box starts in its natural position in the flow, as if it has position: relative. It thus participates in the default flow: if it becomes higher it pushes the paragraphs below it downwards, just like any other regular HTML element. Also, the space it takes in the normal flow is kept open, even if it is currently in fixed position. Scroll down a little bit to see this in action: an empty space is kept open for the header.
A sticky box compares two positions: its natural position in the flow and its fixed position according to its inset properties. It does so in the coordinate frame of its scroll box. That is, any given coordinate such as top: 20px, as well as its default coordinates, is resolved against the content box of the scroll box. (In other words, the scroll box’s padding also constrains the sticky box; it will never move up into that padding.)
A sticky box with top takes the higher value of its top and its natural position in the flow, and positions its top border at that value. Scroll down slowly to see this in action: the sticky box starts at its natural position (let’s call it 20px), which is higher than its defined top (0). Thus it rests at its position in the natural flow. Scrolling up a few pixels doesn’t change this, but once its natural position becomes less than 0, the sticky box switches to a fixed layout and stays at that position.
The sticky box has bottom: 0
Regular content
Regular content
Regular content
Regular content
Regular content
Regular content
Sticky headerContent outside container
Content outside container
Content outside container
Content outside container
Content outside container
Content outside container
It does the same for bottom, but remember that a bottom is calculated relative to the scroll box’s bottom, and not its top. Thus, a larger bottom coordinate means the box is positioned more to the top. Now the sticky box compares its default bottom with the defined bottom and uses the higher value to position its bottom border, just as before.
With left, it uses the higher value of its natural position and to position its left border; with right, it does the same for its right border, bearing in mind once more that a higher right value positions the box more to the left.
If any of these steps would position the sticky box outside its containing box it takes the position that just barely keeps it within its containing box.
Details Sticky headerVery, very long line of content to stretch up the container quite a bit
Regular content
Regular content
Regular content
Regular content
Regular content
Regular content
Content outside container
Content outside container
Content outside container
Content outside container
Content outside container
Content outside container
Content outside container
The four inset properties act independently of one another. For instance the following box will calculate the position of its top and left edge independently. They can be relative or fixed, depending on how the user scrolls.
p.testbox { position: sticky; top: 0; left: 0; }Content outside container
Content outside container
Content outside container
Content outside container
Content outside container
The sticky box has top: 0; bottom: 0
Regular content
Regular content
Regular content
Regular content
Sticky headerRegular content
Regular content
Regular content
Regular content
Regular content
Content outside container
Content outside container
Content outside container
Content outside container
Content outside container
Setting both a top and a bottom, or both a left and a right, gives the sticky box a bandwidth to move in. It will always attempt to obey all the rules described above. So the following box will vary between 0 from the top of the screen to 0 from the bottom, taking its default position in the flow between these two positions.
p.testbox { position: sticky; top: 0; bottom: 0; } No containerRegular content
Regular content
Sticky headerRegular content
Regular content
Regular content
Regular content
Regular content
Regular content
Regular content
Regular content
Regular content
So far we put the sticky box in a container separate from the scroll box. But that’s not necessary. You can also make the scroll box itself the container if you wish. The sticky element is still positioned with respect to the scroll box (which is now also its container) and everything works fine.
Several containers Sticky headerRegular content
Regular content
Regular content
Regular content
Regular content
Regular content
Regular content
Content outside container
Content outside container
Content outside outer container
Content outside outer container
Or the sticky item can be several containers removed from its scroll box. That’s fine as well; the positions are still calculated relative to the scroll box, and the sticky box will never leave its innermost container.
Changing the scroll box Sticky headerThe container has overflow: auto.
Regular content
Regular content
Regular content
Regular content
Regular content
Regular content
Content outside container
Content outside container
Content outside container
One feature that catches many people (including me) unaware is giving the container an overflow: auto or hidden. All of a sudden it seems the sticky header doesn’t work any more.
What’s going on here? An overflow value of auto, hidden, or scroll makes an element into a scroll box. So now the sticky box’s scroll box is no longer the outer element, but the inner one, since that is now the closest ancestor that is able to scroll.
The sticky box appears to be static, but it isn’t. The crux here is that the scroll box could scroll, thanks to its overflow value, but doesn’t actually do so because we didn’t give it a height, and therefore it stretches up to accomodate all of its contents.
Thus we have a non-scrolling scroll box, and that is the root cause of our problems.
As before, the sticky box calculates its position by comparing its natural position relative to its scroll box with the one given by its inset properties. Point is: the sticky box doesn’t scroll relative to its scroll box, so its position always remains the same. Where in earlier examples the position of the sticky element relative to the scroll box changed when we scrolled, it no longer does so, because the scroll box doesn’t scroll. Thus there is no reason for it to switch to fixed positioning, and it stays where it is relative to its scroll box.
The fact that the scroll box itself scrolls upward is irrelevant; this doesn’t influence the sticky box in the slightest.
Sticky headerRegular content
Regular content
Regular content
Regular content
Regular content
Regular content
Regular content
Content outside container
Content outside container
Content outside container
Content outside container
Content outside container
Content outside container
One solution is to give the new scroll box a height that is too little for its contents. Now the scroll box generates a scrollbar and becomes a scrolling scroll box. When we scroll it the position of the sticky box relative to its scroll box changes once more, and it switches from fixed to relative or vice versa as required.
Minor itemsFinally a few minor items:
- It is no longer necessary to use position: -webkit-sticky. All modern browsers support regular position: sticky. (But if you need to cater to a few older browsers, retaining the double syntax doesn’t hurt.)
- Chrome (Mac) does weird things to the borders of the sticky items in these examples. I don’t know what’s going on and am not going to investigate.
Breaking the web forward
Safari is holding back the web. It is the new IE, after all. In contrast, Chrome is pushing the web forward so hard that it’s starting to break. Meanwhile web developers do nothing except moan and complain. The only thing left to do is to pick our poison.
blockquote { font-size: inherit; font-family: inherit; } blockquote p { font-size: inherit; font-family: inherit; } Safari is the new IERecently there was yet another round of “Safari is the new IE” stories. Once Jeremy’s summary and a short discussion cleared my mind I finally figured out that Safari is not IE, and that Safari’s IE-or-not-IE is not the worst problem the web is facing.
Perry Sun argues that for developers, Safari is crap and outdated, emulating the old IE of fifteen years ago in this respect. He also repeats the theory that Apple is deliberately starving Safari of features in order to protect the app store, and thus its bottom line. We’ll get back to that.
The allegation that Safari is holding back web development by its lack of support for key features is not new, but it’s not true, either. Back fifteen years ago IE held back the web because web developers had to cater to its outdated technology stack. “Best viewed with IE” and all that. But do you ever see a “Best viewed with Safari” notice? No, you don’t. Another browser takes that special place in web developers’ hearts and minds.
Chrome is the new IE, but in reverseJorge Arango fears we’re going back to the bad old days with “Best viewed in Chrome.” Chris Krycho reinforces this by pointing out that, even though Chrome is not the standard, it’s treated as such by many web developers.
“Best viewed in Chrome” squares very badly with “Safari is the new IE.” Safari’s sad state does not force web developers to restrict themselves to Safari-supported features, so it does not hold the same position as IE.
So I propose to lay this tired old meme to rest. Safari is not the new IE. If anything it’s the new Netscape 4.
Meanwhile it is Chrome that is the new IE, but in reverse.
Break the web forwardBack in the day, IE was accused of an embrace, extend, and extinguish strategy. After IE6 Microsoft did nothing for ages, assuming it had won the web. Thanks to web developers taking action in their own name for the first (and only) time, IE was updated once more and the web moved forward again.
Google learned from Microsoft’s mistakes and follows a novel embrace, extend, and extinguish strategy by breaking the web and stomping on the bits. Who cares if it breaks as long as we go forward. And to hell with backward compatibility.
Back in 2015 I proposed to stop pushing the web forward, and as expected the Chrome devrels were especially outraged at this idea. It never went anywhere. (Truth to tell: I hadn’t expected it to.)
I still think we should stop pushing the web forward for a while until we figure out where we want to push the web forward to — but as long as Google is in charge that won’t happen. It will only get worse.
On alertA blog storm broke out over the decision to remove alert(), confirm() and prompt(), first only the cross-origin variants, but eventually all of them. Jeremy and Chris Coyier already summarised the situation, while Rich Harris discusses the uses of the three ancient modals, especially when it comes to learning JavaScript.
With all these articles already written I will only note that, if the three ancient modals are truly as horrendous a security issue as Google says they are it took everyone a bloody long time to figure that out. I mean, they turn 25 this year.
Although it appears Firefox and Safari are on board with at least the cross-origin part of the proposal, there is no doubt that it’s Google that leads the charge.
From Google’s perspective the ancient modals have one crucial flaw quite apart from their security model: they weren’t invented there. That’s why they have to be replaced by — I don’t know what, but it will likely be a very complicated API.
Complex systems and arrogant priests rule the webThus the new embrace, extend, and extinguish is breaking backward compatibility in order to make the web more complicated. Nolan Lawson puts it like this:
we end up with convoluted specs like Service Worker that you need a PhD to understand, and yet we still don't have a working <dialog> element.
In addition, Google can be pretty arrogant and condescending, as Chris Ferdinandi points out.
The condescending “did you actually read it, it’s so clear” refrain is patronizing AF. It’s the equivalent of “just” or “simply” in developer documentation.
I read it. I didn’t understand it. That’s why I asked someone whose literal job is communicating with developers about changes Chrome makes to the platform.
This is not isolated to one developer at Chrome. The entire message thread where this change was surfaced is filled with folks begging Chrome not to move forward with this proposal because it will break all-the-things.
If you write documentation or a technical article and nobody understands it, you’ve done a crappy job. I should know; I’ve been writing this stuff for twenty years.
Extend, embrace, extinguish. And use lots of difficult words.
Patience is a virtueAs a reaction to web dev outcry Google temporarily halted the breaking of the web. That sounds great but really isn’t. It’s just a clever tactical move.
I saw this tactic in action before. Back in early 2016 Google tried to break the de-facto standard for the mobile visual viewport that I worked very hard to establish. I wrote a piece that resonated with web developers, whose complaints made Google abandon the plan — temporarily. They tried again in late 2017, and I again wrote an article, but this time around nobody cared and the changes took effect and backward compatibility was broken.
So the three ancient modals still have about 12 to 18 months to live. Somewhere in late 2022 to early 2023 Google will try again, web developers will be silent, and the modals will be gone.
The pursuit of appinessBut why is Google breaking the web forward at such a pace? And why is Apple holding it back?
Safari is kept dumb to protect the app store and thus revenue. In contrast, the Chrome team is pushing very hard to port every single app functionality to the browser. Ages ago I argued we should give up on this, but of course no one listened.
When performing Valley Kremlinology, it is useful to see Google policies as stemming from a conflict between internal pro-web and anti-web factions. We web developers mainly deal with the pro-web faction, the Chrome devrel and browser teams. On the other hand, the Android team is squarely in the anti-web camp.
When seen in this light the pro-web camp’s insistence on copying everything appy makes excellent sense: if they didn’t Chrome would lag behind apps and the Android anti-web camp would gain too much power. While I prefer the pro-web over the anti-web camp, I would even more prefer the web not to be a pawn in an internal Google power struggle. But it has come to that, no doubt about it.
Solutions?Is there any good solution? Not really.
Jim Nielsen feels that part of the issue is the lack of representation of web developers in the standardization process. That sounds great but is proven not to work.
Three years ago Fronteers and I attempted to get web developers represented and were met with absolute disinterest. Nobody else cared even one shit, and the initiative sank like a stone.
So a hypothetical web dev representative in W3C is not going to work. Also, the organisational work would involve a lot of unpaid labour, and I, for one, am not willing to do it again. Neither is anyone else. So this is not the solution.
And what about Firefox? Well, what about it? Ten years ago it made a disastrous mistake by ignoring the mobile web for way too long, then it attempted an arrogant and uninformed come-back with Firefox OS that failed, and its history from that point on is one long slide into obscurity. That’s what you get with shitty management.
Pick your poisonSo Safari is trying to slow the web down. With Google’s move-fast-break-absofuckinglutely-everything axiom in mind, is Safari’s approach so bad?
Regardless of where you feel the web should be on this spectrum between Google and Apple, there is a fundamental difference between the two.
We have the tools and procedures to manage Safari’s disinterest. They’re essentially the same as the ones we deployed against Microsoft back in the day — though a fundamental difference is that Microsoft was willing to talk while Apple remains its old haughty self, and its “devrels” aren’t actually allowed to do devrelly things such as managing relations with web developers. (Don’t blame them, by the way. If something would ever change they’re going to be our most valuable internal allies — just as the IE team was back in the day.)
On the other hand, we have no process for countering Google’s reverse embrace, extend, and extinguish strategy, since a section of web devs will be enthusiastic about whatever the newest API is. Also, Google devrels talk. And talk. And talk. And provide gigs of data that are hard to make sense of. And refer to their proprietary algorithms that “clearly” show X is in the best interest of the web — and don’t ask questions! And make everything so fucking complicated that we eventually give up and give in.
So pick your poison. Shall we push the web forward until it’s broken, or shall we break it by inaction? What will it be? Privately, my money is on Google. So we should say goodbye to the old web while we still can.
Custom properties and @property
You’re reading a failed article. I hoped to write about @property and how it is useful for extending CSS inheritance considerably in many different circumstances. Alas, I failed. @property turns out to be very useful for font sizes, but does not even approach the general applicability I hoped for.
Grandparent-inheritingIt all started when I commented on what I thought was an interesting but theoretical idea by Lea Verou: what if elements could inherit the font size of not their parent, but their grandparent? Something like this:
div.grandparent { /* font-size could be anything */ } div.parent { font-size: 0.4em; } div.child { font-size: [inherit from grandparent in some sort of way]; font-size: [yes, you could do 2.5em to restore the grandparent's font size]; font-size: [but that's not inheriting, it's just reversing a calculation]; font-size: [and it will not work if the parent's font size is also unknown]; }Lea told me this wasn’t a vague idea, but something that can be done right now. I was quite surprised — and I assume many of my readers are as well — and asked for more information. So she wrote Inherit ancestor font-size, for fun and profit, where she explained how the new Houdini @property can be used to do this.
This was seriously cool. Also, I picked up a few interesting bits about how CSS custom properties and Houdini @property work. I decided to explain these tricky bits in simple terms — mostly because I know that by writing an explanation I myself will understand them better — and to suggest other possibilities for using Lea’s idea.
Alas, that last objective is where I failed. Lea’s idea can only be used for font sizes. That’s an important use case, but I had hoped for more. The reasons why it doesn’t work elsewhere are instructive, though.
Tokens and valuesLet’s consider CSS custom properties. What if we store the grandparent’s font size in a custom property and use that in the child?
div.grandparent { /* font-size could be anything */ --myFontSize: 1em; } div.parent { font-size: 0.4em; } div.child { font-size: var(--myFontSize); /* hey, that's the grandparent's font size, isn't it? */ }This does not work. The child will have the same font size as the parent, and ignore the grandparent. In order to understand why we need to understand how custom properties work. What does this line of CSS do?
--myFontSize: 1em;It sets a custom property that we can use later. Well duh.
Sure. But what value does this custom property have?
... errr ... 1em?
Nope. The answer is: none. That’s why the code example doesn’t work.
When they are defined, custom properties do not have a value or a type. All that you ordered the browsers to do is to store a token in the variable --myFontSize.
This took me a while to wrap my head around, so let’s go a bit deeper. What is a token? Let’s briefly switch to JavaScript to explain.
let myVar = 10;What’s the value of myVar in this line? I do not mean: what value is stored in the variable myVar, but: what value does the character sequence myVar have in that line of code? And what type?
Well, none. Duh. It’s not a variable or value, it’s just a token that the JavaScript engine interprets as “allow me to access and change a specific variable” whenever you type it.
CSS custom properties also hold such tokens. They do not have any intrinsic meaning. Instead, they acquire meaning when they are interpreted by the CSS engine in a certain context, just as the myVar token is in the JavaScript example.
So the CSS custom property contains the token 1em without any value, without any type, without any meaning — as yet.
You can use pretty any bunch of characters in a custom property definition. Browsers make no assumptions about their validity or usefulness because they don’t yet know what you want to do with the token. So this, too, is a perfectly fine CSS custom property:
--myEgoTrip: ppk;Browsers shrug, create the custom property, and store the indicated token. The fact that ppk is invalid in all CSS contexts is irrelevant: we haven’t tried to use it yet.
It’s when you actually use the custom property that values and types are assigned. So let’s use it:
background-color: var(--myEgoTrip);Now the CSS parser takes the tokens we defined earlier and replaces the custom property with them:
background-color: ppk;And only NOW the tokens are read and intrepreted. In this case that results in an error: ppk is not a valid value for background-color. So the CSS declaration as a whole is invalid and nothing happens — well, technically it gets the unset value, but the net result is the same. The custom property itself is still perfectly valid, though.
The same happens in our original code example:
div.grandparent { /* font-size could be anything */ --myFontSize: 1em; /* just a token; no value, no meaning */ } div.parent { font-size: 0.4em; } div.child { font-size: var(--myFontSize); /* becomes */ font-size: 1em; /* hey, this is valid CSS! */ /* Right, you obviously want the font size to be the same as the parent's */ /* Sure thing, here you go */ }In div.child he tokens are read and interpreted by the CSS parser. This results in a declaration font-size: 1em;. This is perfectly valid CSS, and the browsers duly note that the font size of this element should be 1em.
font-size: 1em is relative. To what? Well, to the parent’s font size, of course. Duh. That’s how CSS font-size works.
So now the font size of the child becomes the same as its parent’s, and browsers will proudly display the child element’s text in the same font size as the parent element’s while ignoring the grandparent.
This is not what we wanted to achieve, though. We want the grandparent’s font size. Custom properties — by themselves — don’t do what we want. We have to find another solution.
@propertyLea’s article explains that other solution. We have to use the Houdini @property rule.
@property --myFontSize { syntax: "<length>"; initial-value: 0; inherits: true; } div { border: 1px solid; padding: 1em; } div.grandparent { /* font-size could be anything */ --myFontSize: 1em; } div.parent { font-size: 0.4em; } div.child { font-size: var(--myFontSize); }Now it works. Wut? Yep — though only in Chrome so far.
@property --myFontSize { syntax: ""; initial-value: 0; inherits: true; } section.example { max-width: 500px; } section.example div { border: 1px solid; padding: 1em; } div.grandparent { font-size: 23px; --myFontSize: 1em; } div.parent { font-size: 0.4em; } div.child { font-size: var(--myFontSize); } This is the grandparent This is the parent This is the childWhat black magic is this?
Adding the @property rule changes the custom property --myFontSize from a bunch of tokens without meaning to an actual value. Moreover, this value is calculated in the context it is defined in — the grandfather — so that the 1em value now means 100% of the font size of the grandfather. When we use it in the child it still has this value, and therefore the child gets the same font size as the grandfather, which is exactly what we want to achieve.
(The variable uses a value from the context it’s defined in, and not the context it’s executed in. If, like me, you have a grounding in basic JavaScript you may hear “closures!” in the back of your mind. While they are not the same, and you shouldn’t take this apparent equivalency too far, this notion still helped me understand. Maybe it’ll help you as well.)
Unfortunately I do not quite understand what I’m doing here, though I can assure you the code snippet works in Chrome — and will likely work in the other browsers once they support @property.
Misson completed — just don’t ask me how.
SyntaxYou have to get the definition right. You need all three lines in the @property rule. See also the specification and the MDN page.
@property --myFontSize { syntax: "<length>"; initial-value: 0; inherits: true; }The syntax property tells browsers what kind of property it is and makes parsing it easier. Here is the list of possible values for syntax, and in 99% of the cases one of these values is what you need.
You could also create your own syntax, e.g. syntax: "ppk | <length>"
Now the ppk keyword and any sort of length is allowed as a value.
Note that percentages are not lengths — one of the many things I found out during the writing of this article. Still, they are so common that a special value for “length that may be a percentage or may be calculated using percentages” was created:
syntax: "<length-percentage>"Finally, one special case you need to know about is this one:
syntax: "*"MDN calls this a universal selector, but it isn’t, really. Instead, it means “I don’t know what syntax we’re going to use” and it tells browsers not to attempt to interpret the custom property. In our case that would be counterproductive: we definitely want the 1em to be interpreted. So our example doesn’t work with syntax: "*".
initial-value and inheritsAn initial-value property is required for any syntax value that is not a *. Here that’s simple: just give it an initial value of 0 — or 16px, or any absolute value. The value doesn’t really matter since we’re going to overrule it anyway. Still, a relative value such as 1em is not allowed: browsers don’t know what the 1em would be relative to and reject it as an initial value.
Finally, inherits: true specifies that the custom property value can be inherited. We definitely want the computed 1em value to be inherited by the child — that’s the entire point of this experiment. So we carefully set this flag to true.
Other use casesSo far this article merely rehashed parts of Lea’s. Since I’m not in the habit of rehashing other people’s articles my original plan was to add at least one other use case. Alas, I failed, though Lea was kind enough to explain why each of my ideas fails.
Percentage of what?Could we grandfather-inherit percentual margins and paddings? They are relative to the width of the parent of the element you define them on, and I was wondering if it might be useful to send the grandparent’s margin on to the child just like the font size. Something like this:
@property --myMargin { syntax: "<length-percentage>"; initial-value: 0; inherits: true; } div.grandparent { --myMargin: 25%; margin-left: var(--myMargin); } div.parent { font-size: 0.4em; } div.child { margin-left: var(--myMargin); /* should now be 25% of the width of the grandfather's parent */ /* but isn't */ }Alas, this does not work. Browsers cannot resolve the 25% in the context of the grandparent, as they did with the 1em, because they don’t know what to do.
The most important trick for using percentages in CSS is to always ask yourself: “percentage of WHAT?”
That’s exactly what browsers do when they encounter this @property definition. 25% of what? The parent’s font size? Or the parent’s width? (This is the correct answer, but browsers have no way of knowing that.) Or maybe the width of the element itself, for use in background-position?
Since browsers cannot figure out what the percentage is relative to they do nothing: the custom property gets the initial value of 0 and the grandfather-inheritance fails.
ColoursAnother idea I had was using this trick for the grandfather’s text colour. What if we store currentColor, which always has the value of the element’s text colour, and send it on to the grandchild? Something like this:
@property --myColor { syntax: "<color>"; initial-value: black; inherits: true; } div.grandparent { /* color unknown */ --myColor: currentColor; } div.parent { color: red; } div.child { color: var(--myColor); /* should now have the same color as the grandfather */ /* but doesn't */ }Alas, this does not work either. When the @property blocks are evaluated, and 1em is calculated, currentColor specifically is not touched because it is used as an initial (default) value for some inherited SVG and CSS properties such as fill. Unfortunately I do not fully understand what’s going on, but Tab says this behaviour is necessary, so it is.
Pity, but such is life. Especially when you’re working with new CSS functionalities.
ConclusionSo I tried to find more possbilities for using Lea’s trick, but failed. Relative units are fairly sparse, especially when you leave percentages out of the equation. em and related units such as rem are the only ones, as far as I can see.
So we’re left with a very useful trick for font sizes. You should use it when you need it (bearing in mind that right now it’s only supported in Chromium-based browsers), but extending it to other declarations is not possible at the moment.
Many thanks to Lea Verou and Tab Atkins for reviewing and correcting an earlier draft of this article.
Let’s talk about money
Let’s talk about money!
Let’s talk about how hard it is to pay small amounts online to people whose work you like and who could really use a bit of income. Let’s talk about how Coil aims to change that.
Taking a subscription to a website is moderately easy, but the person you want to pay must have enabled them. Besides, do you want to purchase a full subscription in order to read one or two articles per month?
Sending a one-time donation is pretty easy as well, but, again, the site owner must have enabled them. And even then it just gives them ad-hoc amounts that they cannot depend on.
Then there’s Patreon and Kickstarter and similar systems, but Patreon is essentially a subscription service while Kickstarter is essentially a one-time donation service, except that both keep part of the money you donate.
And then there’s ads ... Do we want small content creators to remain dependent on ads and thus support the entire ad ecosystem? I, personally, would like to get rid of them.
The problem today is that all non-ad-based systems require you to make conscious decisions to support someone — and even if you’re serious about supporting them you may forget to send in a monthly donation or to renew your subscription. It sort-of works, but the user experience can be improved rather dramatically.
That’s where Coil and the Web Monetization Standard come in.
Web MonetizationThe idea behind Coil is that you pay for what you consume easily and automatically. It’s not a subscription - you only pay for what you consume. It’s not a one-time donation, either - you always pay when you consume.
Payments occur automatically when you visit a website that is also subscribed to Coil, and the amount you pay to a single site owner depends on the time you spend on the site. Coil does not retain any of your money, either — everything goes to the people you support.
In this series of four articles we’ll take a closer look at the architecture of the current Coil implementation, how to work with it right now, the proposed standard, and what’s going to happen in the future.
OverviewSo how does Coil work right now?
Both the payer and the payee need a Coil account to send and receive money. The payee has to add a <meta> tag with a Coil payment pointer to all pages they want to monetize. The payer has to install the Coil extension in their browsers. You can see this extension as a polyfill. In the future web monetization will, I hope, be supported natively in all browsers.
Once that’s done the process works pretty much automatically. The extension searches for the <meta> tag on any site the user visits. If it finds one it starts a payment stream from payer to payee that continues for as long as the payer stays on the site.
The payee can use the JavaScript API to interact with the monetization stream. For instance, they can show extra content to paying users, or keep track of how much a user paid so far. Unfortunately these functionalities require JavaScript, and the hiding of content is fairly easy to work around. Thus it is not yet suited for serious business purposes, especially in web development circles.
This is one example of how the current system is still a bit rough around the edges. You’ll find more examples in the subsequent articles. Until the time browsers support the standard natively and you can determine your visitors’ monetization status server-side these rough bits will continue to exist. For the moment we will have to work with the system we have.
This article series will discuss all topics we touched on in more detail.
Start now!For too long we have accepted free content as our birthright, without considering the needs of the people who create it. This becomes even more curious for articles and documentation that are absolutely vital to our work as web developers.
Take a look at this list of currently-monetized web developer sites. Chances are you’ll find a few people whose work you used in the past. Don’t they deserve your direct support?
Free content is not a right, it’s an entitlement. The sooner we internalize this, and start paying independent voices, the better for the web.
The only alternative is that all articles and documentation that we depend on will written by employees of large companies. And employees, no matter how well-meaning, will reflect the priorities and point of view of their employer in the long run.
So start now.
In order to support them you should invest a bit of time once and US$5 per month permanently. I mean, that’s not too much to ask, is it?
ContinueI wrote this article and its sequels for Coil, and yes, I’m getting paid. Still, I believe in what they are doing, so I won’t just spread marketing drivel. Initially it was unclear to me exactly how Coil works. So I did some digging, and the remaining parts of this series give a detailed description of how Coil actually works in practice.
For now the other three articles will only be available on dev.to. I just published part 2, which gives a high-level overview of how Coil works right now. Part 3 will describe the meta tag and the JavaScript API, and in part 4 we’ll take a look at the future, which includes a formal W3C standard. Those parts will be published next week and the week after that.