• maiweb v0.1.0
  • ★
  • Feedback

css-tricks.com

Visit site ↗

All items hosted on this domain, most recent first.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-17 15:32
    ↗

    There's a brand new ariaNotify() method — defined by the WAI-ARIA 1.3 Specification — that provides a means of programmatically triggering narration in a screen reader. The Siren Song of ariaNotify() originally handwritten and published with love on CSS-Tricks. You should...

    I need you all to promise me you’ll be cool about this. I‘m here to tell you about an upcoming web platform feature that has been a long time coming; a feature that not only fulfills a use case sorely overdue for a better solution, but does so by way of a syntax that is both immediately understandable and deceptively powerful. That’s right, this thing is developer catnip, and I don’t mind saying that I was really excited to try it out — after which point I willed myself to tuck it away in a drawer and put it out of my mind. This is a tool only to be used in situations where it is absolutely, one hundred percent necessary, to solve a problem that cannot be solved in any other way, up to and including “push back against building a feature in the first place.” So just be cool about this, okay? Okay.

    There’s a brand new ariaNotify() method — defined by the Accessible Rich Internet Applications (WAI-ARIA) 1.3 Specification — that provides you with a means of programmatically triggering narration in a screen reader. It accepts a string as its first argument, and an optional configuration object as its second:

    document.ariaNotify( "Hello, World." );
    // When invoked, a screen reader will narrate "Hello, World."

    That might look like a simple solution to an equally simple use case here in print, but historically this has a tricky problem that could only be solved by slightly off-label usage of ARIA’s live regions. That means that understanding live regions — and their shortcomings — is the key to understanding what ariaNotify does for us. If you’ve worked with live regions before, you likely closed this tab right after that code snippet, and you’re currently on your third or fourth lap around the room with your arms held aloft in triumph. If you haven’t worked with live regions before, well, to put it in the strictest possible technical terms: woof what a mess.

    In an assisted browsing context, if some part of a page changes in response to a user interaction, or something is loaded and added to the page asynchronously, those changes aren’t discoverable until the user moved their focus to that changed content — a user would have no way of knowing that something had changed, let alone what. Live regions address that, at least by design: an element with an aria-live attribute will prompt narration for changes to the markup contained within that element — when the markup is changed, the changed markup is narrated aloud. If aria-live has a value of assertive, it informs assistive technology “this is urgent, and should be narrated right away.” If aria-live has a value of polite, it says “this should be narrated, at the next natural opportunity to do so.” Using role="alert" or role="status" on an element is functionally equivalent to aria-live="assertive" and aria-live="polite", respectively. Sounds pretty reasonable on paper, right?

    Naturally, we needed a way to fine-tune exactly what information is narrated and how, so there are a few other attributes that determine a live region’s behavior:

    aria-atomic

    • true: narrate the entire contents of the live region when something in it changes
    • false (default): announce only the text that changes within the element

    aria-relevant

    • text: notify the user when phrasing content — text, just like it says on the tin — changes inside the live region
    • additions: notify the user when a node is added to the live region
    • removals: notify the user when a node is removed from the live region
    • all (default): notify the user if text is changed, and/or elements are added to or removed from the DOM

    Again, solid enough in theory! Problem solved, right up until the point where you try to use live regions, for pretty much anything, ever. In practice, browsers and assistive technologies are wildly inconsistent about implementation, particularly as it relates to nested markup within a live region — if you want aria-live to work as expected, you’ll often end up needing to strip out all the otherwise semantically-meaningful markup that you should be using. In order to work reliably across assisted browsing contexts, a live region has to already meaningfully exist in the DOM at the time the narration is triggered. A live region can’t be toggled from display: none or injected into the page along with the content to be narrated or you’ll run into timing issues that prevent the content from being narrated — when the browser first “sees” the live region, it locks in “okay, narrate anything that changes in this container,” which doesn’t necessarily include that initial content. The way the "assertive" and "polite" values work isn’t especially well-defined in the specification or realized across screen readers and browser combinations, either. Again: they’re a mess.

    Even if all that weren’t the case, there’s a fundamental mismatch between the purpose of live regions and the way the modern web is built. Like I said, live regions only work when markup is added to/removed from the element in question, and that isn’t the reality of most interactions that result in a change to the visible contents of a page. Live regions are no help when you’re revealing markup that’s already in the document, but otherwise inert — for example, swapping between a visible display property and display: none. That use case is every bit as common as structural changes to the current document on-the-fly, if not more so.

    All these limitations have led to live regions almost exclusively being used as makeshift notification APIs: having one or more aria-live elements buried in the page, visually hidden (but not removed from the accessibility tree via display: none), that you update as-needed with whatever text you want narrated. I have been there and done this, and it’s clunky, not least of all because of how inconsistent live regions are at their core. That injected content is also necessarily available to a user navigating through the page via assistive tech, just floating in the document divorced from it’s original meaning — if you’re not meticulous about cleaning up afterwards, you’ve added a potentially confusing source of contextually-irrelevant narration to the page. Most of all, though, you’ve added a new and invisible concern; a feature that will need dedicated testing and upkeep, and something that can break in very literally unseen ways, and do so in ways that have the potential to be annoying, misleading, confusing, or all of the above. That’s what gets you, with accessibility work: quick-and-easy decisions made in isolation can have unforeseen consequences in the context of the overall experience, and unless those assumptions are tested very carefully — early and often — we can’t know what those consequences might be.

    The ariaNotify method takes the place of this kind of Rube Goldberg accessibility contraption, providing you with a real screen reader notification API, no convoluted (and flaky) markup required:

    document.ariaNotify( "Hello, World." );

    ariaNotify is available as a method on the Element interface or on the Document interface — there’s no meaningful difference between the two for the examples you’re going to see here, but it’s worth knowing that calling document.ariaNotify() means that the lang attribute specified on the html element, specifically, will be used to infer the language of the notification:

    const btn = document.querySelector( "button.announce" );
    
    btn.addEventListener("click", function( e ) {
      document.ariaNotify( "Hello, World." );
    });
    /*
    * Clicking the button results in the "polite"-timed announcement "hello, world," 
    * using the `lang` attribute specified on the `<html>` element. If there isn't 
    * one, the browser's default language is used.
    /*

    While calling ariaNotify() from an element means that the lang attribute of the element’s nearest ancestor will be used to determine the language of the notification:

    const btn = document.querySelector( "button.announce" );
    
    btn.addEventListener("click", function( e ) {
      this.ariaNotify( "Hello, World." );
    });
    /*
    * Clicking the button results in the "polite"-timed announcement "hello, world," 
    * using the `lang` attribute of the `button` (or the closest parent element with 
    * `lang`) to  determine pronunciation. If there isn't one in the document (all
    * the way up to and including `<html>`), the browser's default language is used.
    /*

    ariaNotify accepts a second parameter that allows you to set an explicit priority level:

    const btn = document.querySelector( "button.announce" );
    
    btn.addEventListener("click", function( e ){
      this.ariaNotify( "Hello, world.", {
        priority: "high"
      });
    });

    The default priority for these notifications is priority: "normal", which behaves like aria-live="polite" (or role="status"). Setting an explicit priority: "high" will prioritize and potentially interrupt the current narration, the way aria-live="assertive" (or role="alert") would.

    That’s the entire API so far, right there. No fussing with markup, no finessing timings; if you need something narrated, you call ariaNotify and it is narrated, just like that. You can try this out in Firefox as we speak, though it doesn’t seem like lang attributes are factored in just yet:

    CodePen Embed Fallback

    JAWS

    Polite, button. To activate, press space bar. [spacebar pressed] Space. Hello, World.

    Assertive, button. To activate, press space bar. [spacebar pressed] Space. Hello, World.

    Educado [pronounced correctly], button. To activate, press space bar. Space. Hola, Mundo [pronounced incorrectly].

    NVDA

    Polite, button. [spacebar pressed] Hello, World.

    Assertive, button. [spacebar pressed] Hello, World.

    Educado [pronounced correctly], button. [spacebar pressed] Hola, Mundo [pronounced incorrectly].

    VoiceOver

    Polite, button. You are currently on a button [spacebar pressed] inside of a frame. To click this button, press Control–Option–Space. To exit this web area, press Control–Option–Shift-Up Arrow. Hello, World.

    Assertive, button. You are currently on a button [spacebar pressed] Hello, World.

    Educado [pronounced correctly], button. You are currently on a button [spacebar pressed] inside of a frame. To click this button, press Control–Option–Space. To exit this web area, press Control–Option–Shift-Up Arrow. Hola, Mundo [pronounced incorrectly].

    Pretty solid, huh? Huge improvement over how we’ve all been stuck using live regions. I, for one, can’t wait to almost use ariaNotify, then — again — promptly talk myself out of it!

    Why the reluctance? Well, in accessibility circles, it is sometimes said that there are three stages of learning to use ARIA:

    1. You don’t use ARIA.
    2. You use ARIA.
    3. You don’t use ARIA.

    The W3C puts this in more formal terms, as is their specialty:

    If you can use a native HTML element [HTML] or attribute with the semantics and behavior you require already built in, instead of re-purposing an element and adding an ARIA role, state or property to make it accessible, then do so.

    —Using ARIA: First Rule of ARIA Use

    That second stage of ARIA mastery is where we get ourselves into trouble. The web is a chaotic place, but assistive technologies have evolved alongside it, and they’ve learned to paper over some of the more common issues a user might encounter. For example, say you have an h2 that reveals some visually-hidden content that follows it when clicked — that element might be presented in a way that makes that interaction clear visually, but without our intervention, it might not otherwise be signaled to a user browsing via screen reader. To work around this, assistive technologies can helpfully narrate that heading element as “clickable” when it receives user focus upon finding a click event listener bound to that heading. Granted, that isn’t as good as explicitly signaling the purpose of this element to the user, but it is workable, even if we didn’t make that interaction explicit.

    The catch is in how we that make that interaction explicit. If you‘re somewhat familiar with ARIA, you might find yourself thinking “well, this element behaves like a button, so I should put role="button" on it to inform a user that this does something.” That impulse isn’t strictly wrong, but with that attribute comes a likely unintended consequence: by being explicit about the element’s role, we remove its implicit meaning. You’re telling the browser and assistive technology, in no uncertain terms, that this is not a heading — so if the user is navigating by way of the document outline, this element will no longer be part of that navigation, and what felt like a simple, helpful quick-fix ends up having an unintended consequence. ARIA leaves no room for interpretation; what we say goes, full stop. We say “narrate this,” it gets narrated. Non-negotiable.

    So, given a very easy-to-use feature that inarguably says “when I tell you to narrate this, you narrate it,” please assume that I am making steely, unblinking eye contact here while I say, aloud, “alert()” — an imagined scenario made all the more unsettling by the fact that I have somehow managed to say it in a monospaced font.

    window.alert( "Hello world, like it or not." );

    You remember alert() from way back in the day, right? A method as infamous as it is obnoxious. If you’re newer to the industry, you might not be familiar with it first-hand, for a blessing. Like ariaNotify, it was — is, technically — a quick and easy API for immediately presenting information to a user:

    A CSS-Tricks article with an alert on top that identifies the site address and says 'Hello World, like it or not.'

    alert() is simple, effective, consistent, and — back when it saw widespread usage — incredibly annoying. ariaNotify() entrusts you with this same power, this time backed by the invisible, unyielding authority of ARIA. With ariaNotify() in your pocket, “this might be confusing, so I’ll narrate exactly what’s going on” will be a quick and easy decision, and might mean that a savvy user — already skilled at navigating the web despite all its inherent chaos and inconsistency — finds their browsing interrupted by a lecture about an interaction they already understand.

    It isn’t hard to imagine a developer — their heart squarely in the right place — using ariaNotify to inform a user that content has been revealed by an interaction on the page. In context, however, revealing that content likely meant interacting with an element already narrated as “clickable” thanks to the presence of an associated event listener, the element’s inherent semantics, or the presence of an aria-expanded="false" attribute (the correct approach to signaling that interacting with an element will reveal associated content). In that case, all we’ve done is add noise to the user’s experience of the page, and nobody needs that. I mean, imagine being partway through reading this sentence when alert( "There's a new comment on this article!" ) interrupts you for the third time, or hovering over <button>Navigation</button> only to get hit with alert( "Click here to open the navigation." ) like some unskippable video game tutorial? Ugh. I’d close the tab.

    Even worse, if a narrated instruction falls out of sync with the reality of the interaction itself — an invisible inconsistency that wouldn’t be caught by a QA process that lacks dedicated screen reader testing — we could end up making the user sit through an argument between the underlying page and their own screen reader while they’re just trying to get things done and get on with their day.

    ARIA is powerful stuff. It gives us the ability to define the meanings, states, and relationships between elements on a page as absolute, iron-clad fact — it provides a line of communication between those of us building the web and those of us using it. Nowhere is that line of communication more direct than with ariaNotify(), a feature that effectively allows us to speak directly to an end user using the voice of the browser and assistive technology they know and trust. That’s a lot of responsibility bound up in a single method. It solves a very real problem, but like so many technologies: if not used carefully, it can cause just as many.

    I am excited about ariaNotify(), y’know, in a measured, cautious way. It finally gives us a way to address a use case that has plagued the web — and me, personally — for years, in a shockingly easy way. So easy, in fact, that it makes ariaNotify() just a little bit dangerous.

    I mean, not for us though, right? Because we’re all gonna be cool about this, right?

    Right.


    The Siren Song of  ariaNotify() originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-16 18:36
    ↗

    Props for That creates live props based things CSS can't normally see in the browser. Things like cursor position, progress values, certain form states, current time, scroll velocity. Prop For That originally handwritten and published with love on CSS-Tricks. You should...

    No secret that Adam’s all about props. Dude gave us Open Props a good while back for a slew of preconfigured variables for color, shadows, sizing, typography, among much much more. Now he’s back with Prop For That, a similar sorta idea, but mind-blowing in the sense that it creates live props based things CSS can’t normally see in the browser. Things like cursor position, progress values, certain form states, current time, scroll velocity — you know, the stuff that JavaScript sniffs and passes to CSS.

    My understanding is that all the script-y stuff is already in the background. All that’s needed is to import the library, declare it in HTML, then style away in CSS.

    Like, here’s Chris a long while back with custom properties registered in JavaScript to track cursor position:

    CodePen Embed Fallback

    Prop For That has that nicely covered. The difference is that we’re working with data attributes that trigger the scripts:

    <div class="mover" data-props-for="pointer">...</div>

    And plop the relevant props into the styles:

    .mover {
      aspect-ratio: 1;
      width: 50px;
      background: red;
      position: absolute;
      left: calc(var(--live-pointer-x, 0) * 1px);
      top: calc(var(--live-pointer-y, 0) * 1px);
    }
    CodePen Embed Fallback

    The demos are where it’s at. Good lord, can Adam put together some classy work.


    Prop For That originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-15 13:15
    ↗

    CSS functions, the alpha() function, Grid Lanes, some things about Dialog that you might not know, CSS Wordle, and more — this is What’s !important right now. What’s !important #13: @function, alpha(), CSS Wordle, and More originally handwritten and published with love on...

    CSS functions, the alpha() function, Grid Lanes, some things about <dialog> that you might not know, CSS Wordle, and more — this is What’s !important right now.

    CSS functions, expertly explained

    Jane Ori expertly explained how CSS functions work. @function will probably be the biggest CSS feature to probably become Baseline this year, so I definitely found it a bit intimidating at first. That is, until I read Jane’s baby-step-by-baby-step walkthrough, which eases you into it really well.

    In addition, Declan Chidlow wrote our @function documentation, which you might want to bookmark for quick reference in the future.

    The alpha() function

    Speaking of functions, the alpha() function caught me by surprise. Firstly, because I hadn’t heard of it, and secondly, because…why? We can already change the alpha channel:

    /* This */
    color: alpha(from var(--color) / 0.5);
    
    /* Instead of this */
    color: oklch(from var(--color) l c h / 0.5);

    Well, this comment from Jason Leo sums it up. Firstly, it means that we won’t need to hard-code color values when we already have CSS variables. For years I’ve circumvented this by only storing the actual values in CSS variables, but having to wrap them in the color function every single time is really monotonous:

    /* Just the values */
    --color: 0.65 0.23 230;
    
    /* Then use them flexibly */
    color: oklch(var(--color));
    color: oklch(var(--color) / 0.5);

    But it’s better than this (in my opinion):

    /* Function and values */
    --color: oklch(0.65 0.23 230);
    
    /* Delightful */
    color: var(--color);
    
    /* Delightless */
    color: oklch(from var(--color) l c h / 0.5);

    alpha() offers the best of both worlds:

    /* Less delightless */
    color: alpha(from var(--color) / 0.5);

    Secondly, the color format is actually irrelevant in this context, so alpha(from var(--color) / 0.5) communicates the intention more clearly than oklch(from var(--color) l c h / 0.5) does. It also makes the declaration inherently shorter.

    Credit to Adam Argyle for bringing alpha() up.

    The Field Guide to Grid Lanes

    WebKit launched the Field Guide to Grid Lanes (formerly known as CSS masonry layout). If you’ve ever read one of our CSS-Tricks Guides, it’s similar to that (their words — just sayin’). It’s a smooth introduction with a variety of barebones and real-world demos.

    Six CSS Grid Lanes demos organized in a three-by-two grid — Photos, Recipes, Newspaper, Mega Menu, Timeline, and Pinboard.
    Source: WebKit.

    Quality-of-life upgrades for <dialog>

    Una Kravets talked about two quality-of-life upgrades for <dialog> — the new closedby attribute, which isn’t supported by Safari yet, and overscroll-behavior: contain. There are some nuggets in the comments too, including a tip about scrollbar-gutter: stable.

    ✅ Nice lil btn scale-down 🙈 Layout change bc the scroll bar disappears 🙈 No light dismiss These UX problems can easily be solved with: – closedby="any" – overscroll-behavior: contain

    [image or embed]

    — Una Kravets (@una.im) 13:28 · Jun 3, 2026

    Also, Chris Coyier showed us how to animate <dialog>s, which I think many of us know how to do already, but it’s so easy to mess up. I have to Google it every time (it’s those bleeping @starting-styles).

    What happened at CSS Day 2026?

    CSS Day, the annual CSS community conference, was held in Amsterdam on the 11th and 12th of this month (so two days, technically). While there wasn’t a livestream this year, recordings will become available in late June. Until then, check out CSS Day on Bluesky as well as the #CSSDay Bluesky feed to see what happened on stage, what happened behind the scenes, and even the slides from some of the talks.

    Portrait photos of the event speakers for CSS Day 2026.
    Source: CSS Day.

    And no, there weren’t any flamethrowers this year, but it wasn’t DOOM-free either (if you know, you know).

    CSS Wordle

    What a week it’s been, especially with everything that transpired at CSS Day, but if you have any energy left I highly recommend a round (or several rounds) of Sunkanmi Fafowora’s CSS Wordle, which I’ve literally been obsessed with for the last week.

    An online game interface for CSS Wordle featuring a completed puzzle.
    Source: CSS-Questions (don’t worry, this was yesterday’s answer).

    New web platform features and updates

    • Chrome 149
      • Gap decorations (now Baseline)
      • image-rendering: crisp-edges (now Baseline)
      • rect() and xywh() for shape-outside (now Baseline)
      • path() and shape() for shape-outside (no Safari or Firefox support)

    Until next time!


    What’s !important #13: @function, alpha(), CSS Wordle, and More originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-12 15:09
    ↗

    Why isn't my 3D view transition working?! Sunkanmi tackles this frustration and offers an elegant fix for it. Why Isn’t My 3D View Transition Working? originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

    If you have played around with view transition a bunch, you may have noticed that 3D transitions between two pages (i.e., cross-document view transitions) don’t seem to work. That is, at least not without the browsers flattening things first.

    Image elements are the best example to demonstrate this because, like the snapshots a browser takes of the before-after states in a view transition, images are replaced elements so, in theory, we should be able to use them as a sort of reduced test case for 3D animations. For example, flipping one image to reveal another on click looks like this:

    CodePen Embed Fallback

    It’s important to note that, for the animation to work properly, we need to set the perspective property on the image’s parent container (in our case, it’s the .scene element). Otherwise, the 3D transformation is merely flat. It sort of angles the element’s appearance:

    CodePen Embed Fallback

    In CSS, the parent’s persepective is applied to all its children, excluding itself:

    .scene {
      perspective: 1200px;
    
      .card { /* gets perspective */ }
    }

    What’s important here is the HTML structure. Specifically how the .scene container sits on top of the child .card elements, making the 3D effect come to life so the flip looks how it should:

    <div class="scene">
      <div class="card">
        <!-- Card Content Here -->
      </div>
    </div>

    Perhaps our keyframe animation to flip the .cards is something like this:

    @keyframes flipOut {
      from {
        transform: rotateY(0deg);
      }
      to {
        transform: rotateY(-90deg);
      }
    }

    Which we apply to the .cards like this:

    .card.flip-out {
      animation: flipOut 5.2s cubic-bezier(0.4, 0, 0.2, 1) forwards;
    }
    .card.flip-in {
      animation: flipOut 5.2s cubic-bezier(0.4, 0, 0.2, 1) forwards reverse;
    }

    …where the animates runs forwards when the .flip-out class is appended to the .card (courtesy of JavaScript watching for a click) and runs in reverse when the .flip-in class is appended.

    That’s the setup for how a cross-document view transition ought to work, too, right? If an image supports a 3D animation, then a view transitions snapshot should do the same. Let’s poke at that.

    Setting up the view transition

    First things first, we have to opt into view transitions on both pages with the @view-transition at-rule by setting the navigation descriptor to auto:

    @view-transition {
      navigation: auto;
    }

    If we were to do nothing else, then one page fades into another when navigating between the two. It’s the most basic of all cross-document view transitions.

    How do we customize things? We use the ::view-transition-old() and ::view-transition-new() pseudo-classes, where the former is the “old” snapshot and the latter is the “new” one. Like the .card elements we used in the last example, that’s where we set the keyframe animation:

    ::view-transition-old(root) {
      /* animation goes here */
    }
    
    ::view-transition-new(root) {
      /* animation goes here */
    }

    The root parameter tells the view transition to target the whole page and all the elements created (and not created) by the view transition’s default snapshot group.

    Here’s the problem

    Let’s say we want to apply that same 3D flip to the entire webpage, where the snapshot of the “old” page flips into the “new” page. Again, a 3D animation asks us for two things:

    1. The perspective property on the parent element so its children get that 3D effect
    2. An animation on the page for when the view transition happens

    But: What exactly do we set the perspective on, as in, what is the parent element here?

    Since view transitions take snapshots of the entire webpage, we might assume (logically) it would be the <html> element (or the :root), right? I mean, the DOM tree looks like this when a view transition is present:

    html
      ├─ ::view-transition
      │  ├─ ::view-transition-group(card)
      │  │  └─ ::view-transition-image-pair(card)
      │  │     ├─ ::view-transition-old(card)
      │  │     └─ ::view-transition-new(card)
      │  └─ ::view-transition-group(name)
      │     └─ ::view-transition-image-pair(name)
      │        ├─ ::view-transition-old(name)
      │        └─ ::view-transition-new(name)
      ├─ head
      └─ body
            └─ …

    So, the entire snapshot should be where we put the perspective. Right? Turns out, no.

    In fact, does nothing at all! You’re left with this instead of the beautiful 3D flip we were able to use on the cards earlier:

    GitHub Source and Live Demo

    Here’s the code I was working with:

    /* Cross-document View Transition opt-in */
    @view-transition {
      navigation: auto;
    }
    
    /* 3D flip: Old page flips away, new page flips in */
    @keyframes flip-out {
      0% {
        transform: rotateY(0deg);
        opacity: 1;
      }
      100% {
        transform: rotateY(-90deg);
        opacity: 0;
      }
    }
    
    @keyframes flip-in {
      0% {
        transform: rotateY(90deg);
        opacity: 0;
      }
      100% {
        transform: rotateY(0deg);
        opacity: 1;
      }
    }
    
    ::view-transition-old(root) {
      animation: flip-out 0.3s cubic-bezier(0.4, 0, 1, 1) forwards;
      transform-origin: center center;
    }
    
    ::view-transition-new(root) {
      animation: flip-in 0.3s cubic-bezier(0, 0, 0.6, 1) 0.3s backwards;
      transform-origin: center center;
    }

    Note: I didn’t reverse the animation here since we flip to -90deg and then from 90deg. Not exactly the same!

    And it doesn’t work, no matter if perspective is on html or :root:

    /* 👎 */
    html {
      perspective: 1100px;
    }
    
    /* 👎 */
    :root {
      perspective: 1100px;
    }

    I did some digging and discovered that perspective (and 3D transformations in general) is one of several CSS properties that would produce an unusual effect. (Leave it to Bramus to have the answer!)

    So… What do we do? Some ideas came to mind, but sadly failed:

    • I tried setting the perspective property on the body.
    • I tried setting perspective inside ::view-transition-group(root).
    • I tried setting perspective inside the ::view-transition pseudo.

    There’s actually a super simple workaround to this, and I can’t believe it took me this long to figure it out — don’t use perspective at all!

    The solution

    Short story: we have to use the perspective() function instead of the perspective property. And not inside any of the ::view-transition-* pseudos as you might expect, but inside the @keyframes animation:

    @keyframes flip-out {
      0% {
        transform: perspective(1100px) rotateY(0deg);
        opacity: 1;
      }
      100% {
        transform: perspective(1100px) rotateY(-90deg);
        opacity: 0;
      }
    }
    @keyframes flip-in {
      0% {
        transform: perspective(1100px) rotateY(90deg);
        opacity: 0;
      }
      100% {
        transform: perspective(1100px) rotateY(0deg);
        opacity: 1;
      }
    }

    This simple, but big change moves the scene from a flat meh to a beautiful ah yeah:

    GitHub Source and Live Demo

    Here’s why, apparently. The view transition pseudo-element tree is rendered outside the normal HTML flow. More specifically, the entire view transition tree is rendered above the DOM in its own layer. However, particularly for ::view-transition, I’m not too sure why this is the case, but my best guess would be that each view transition group automatically has its position and transform values overridden by the browser; hence, interfering with the perspective.

    The difference between perspective and perspective()? The perspective property is applied to the parent element, while perspective() is a transform property function applied directly to the element itself. And since the view transition pseudo tree does not have a true parent, we’ve gotta use perspective() since it doesn’t require a parent. Phew.

    To recap…

    Setting perspective on the html, :root, or any of the view transition pseudo-class won’t work. And if you have been struggling to find the solution, like I was, I think this little, but big perspective() change will solve that issue if you ever come across it. Take it from me, I battled with this for weeks till I came back today to rant about it and discovered a solution to it. A perk of writing!


    Why Isn’t My 3D View Transition Working? originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-12 15:08
    ↗

    One of those nuances to keep in your back pocket when writing for screen readers. There’s no need to include ‘navigation’ in your navigation labels originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

    Mark Underhill:

    And now to the reason I wrote this post: including the word “navigation” in your <nav> labels. There’s no need. If we did, we’d hear something like “Navigation, Primary navigation”. Not the end of the world, but unnecessarily repetitive for screen reader users.

    One of those nuances to keep in your back pocket when writing for screen readers. Reminds me, too, that there’s no need to say something like “image” when describing one in the alt text. That’s sorta implied. While I’m no screen reading native, I imagine these sorts of things are minor pet peeves that, given a little love and consideration, make navigating that much more enjoyable.

    While we’re on the UX of accessible text, another consideration: keep it succinct. It doesn’t have to be a novel.


    There’s no need to include ‘navigation’ in your navigation labels originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-10 13:02
    ↗

    There are many ways to create memorable experiences. Sometimes it's as simple as a form that completes smoothly. But here I'm interested in sharing techniques I reach for when I want a site to feel alive and be remembered. Creating Memorable Web Experiences: A Modern CSS...

    I love the fact that CSS is finally reclaiming control over visual interactions, taking charge of the styling, the animation, and the accessibility exactly as it should. Today, native browser capabilities allow us to move the heavy lifting away from the JavaScript main thread and closer to the GPU. By letting the browser’s engine optimize performance under the hood, we save energy and processing power while building code that is robust, accessible, and independent of external libraries that might deprecate tomorrow.

    We have 3D, modern layout techniques, clip-paths, transforms, custom properties, scroll-driven animations, view-transitions, @property — and we can animate almost anything, even to auto-height!

    And, of course, there’s SVG, which isn’t new, but allows us to build entire websites through illustrations and animations. Take the example below: it’s responsive, lightweight, accessible, and powered primarily by CSS Grid + SVG.

    We can even build an entire video game including the UI using only SVG:

    What follows is not a complete guide to modern CSS, but an opinionated selection of techniques I reach for when I want a site to feel alive and be remembered. There are many ways to create memorable experiences. Sometimes it’s as simple as a form that completes smoothly. But here I’m interested in the expressive end of the spectrum.

    Motion as Communication: Defining Your Intent

    Before we dive into the technical side, I want to clarify something: we shouldn’t move things just because we can.

    Everything communicates, and our animations are no exception. We must take the time to design movements that support the message we want to convey in order to keep our intents tightly scoped without overdoing it.

    Here’s a methodology I use when planning the design and animation of a site.

    Imagine we’re working on a project for a nature event focused on mushrooms. The design language changes completely depending on the “vibe”: selling a “Psychedelic Mushroom Rave” is worlds apart from a “Spiritual Mushroom Retreat” focused on ancestral medicine.

    Every design decision communicates. I like to create what I call keyword lists to define my intent and scope. For example, I might break things down into different options:

    Option A: The Psychedelic Event

    • Visuals: Colorful, saturated, high-contrast, illustrations, distortions
    • Movement: Fast, frantic, unpredictable, morphing, rhythmic, synced loops, hypnotic
    • Feeling: Fun, chaotic, energetic, stimulating, surprising
    • Typography: Funk, “psych-rock”
    • Style References: Pop Art, 60s/70s op art, rave flyers
    • Actions: Dancing
    • Extras: Emojis, films (e.g., Fear and Loathing in Las Vegas)

    Option B: The Spiritual Retreat

    • Visuals: Earth tones, neutral tones, de-saturated, photograph-heavy, nature, whitespace
    • Movement: Slow, fluid, organic, breathing, subtle parallax, smooth scrolling.
    • Feeling: Calm, serene, introspective, contemplative, safe
    • Typography: Elegant Serif, minimalist sans-serif, wide spacing, legible
    • Style References: Scandinavian design, Japanese Wabi-sabi, wellness/spa aesthetics, botanical books
    • Actions: Breathing
    • Extras: Healing sounds, film (e.g., Eat Pray Love)

    This is the kind of exercise I do to guide my design and animation decisions. The lists will help me select everything from which CSS properties I plan to use and how to use them. I even share them with the client and, together, we choose a direction.

    Let’s say we go with Option A and look at a few examples of what I think are essential ingredients for creating memorable user experiences.

    Split Text Animations

    These animations became popular thanks to the GSAP SplitText plugin. It splits text by character (or words, or lines if you like) so we can create interesting text effects, like staggered animations.

    <h1 class="reveal-text">
      <span style="--i:0">H</span>
      <span style="--i:1">O</span>
      <span style="--i:2">L</span>
      <span style="--i:3">A</span>
    </h1>

    This approach wraps each letter in “Hola” in a span. From there, each span is inline-styled with a custom property indexing the spans in order. Which is something that will get a lot easier when the sibling-index() function gains broad browser support.

    But for now, each custom property value acts as a multiplier that increases an animation-delay, staggering each span. In this case we fade in each character as it moves up.

    .reveal-text span {
      animation: slideUp 0.6s ease-out forwards;
      animation-delay: calc(var(--i) * 0.1s);
      display: inline-block;
      opacity: 0;
      transform: translateY(3rem);
    }
    
    @keyframes slideUp {
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    Accessibility is the tricky part here. The instinct is to hide all the individual spans from assistive technology with aria-hidden="true" and add a visually hidden version of the full word for screen readers:

    <h1>
      <span class="sr-only">HOLA</span>
      <span aria-hidden="true" class="reveal-text">
        <span style="--i:0">H</span>
        <span style="--i:1">O</span>
        <span style="--i:2">L</span>
        <span style="--i:3">A</span>
      </span>
    </h1>
    .sr-only {
      position: absolute;
      width: 1px;
      height: 1px;
      padding: 0;
      margin: -1px;
      overflow: hidden;
      clip: rect(0, 0, 0, 0);
      white-space: nowrap;
      border: 0;
    }

    But be warned: this pattern doesn’t guarantee a good experience across all screen readers. Adrian Roselli tested GSAP’s SplitText across eight screen reader and browser combinations and found it only worked correctly in two of them. If you ship this technique, test it with real assistive technology.

    If that risk feels too high, there’s a very clever alternative from Preethi worth knowing that uses the letter-spacing property. It accepts negative values that collapse characters on top of each other, hiding them without touching the DOM at all. Animate it back to 0 and you get a similar reveal effect without accessibility overhead.

    What would be great is a pseudo-selector like ::nth-letter to target individual glyphs directly from CSS the way ::first-letter selects the first character. But unfortunately, there’s no ::nth-letter… at least yet.

    Remember to respect the user’s motion preferences on every animation:

    @media (prefers-reduced-motion: reduce) {
      .reveal-text span {
        animation: none; /* or a softer animation */
      }
    }

    And here we go:

    CodePen Embed Fallback

    It might not scale too much when we have a lot of text and different animations we want to apply. For the psychedelic event, I wanted to try splitting text with SMIL, but it was verbose. This is the code for animating two letters alone:

    <svg role="img" aria-label="TODOS LOS HONGOS" viewBox="0 0 1366 938.96">
      <title>TODOS LOS HONGOS</title>
      <g aria-hidden="true">
        <text transform="rotate(-9.87 2181.107 -1635.1)" opacity="0">T
          <animate attributeName="dy" values="100; -20; 0" keyTimes="0; 0.8; 1" dur="0.4s" begin="0s" fill="freeze"/>
          <animate attributeName="opacity" from="0" to="1" dur="0.01s" begin="0s" fill="freeze"/>
        </text>
        <text transform="rotate(-8.92 2372.854 -2084.755)" opacity="0">O
          <animate attributeName="dy" values="100; -20; 0" keyTimes="0; 0.8; 1" dur="0.4s" begin="0.1s" fill="freeze"/>
          <animate attributeName="opacity" from="0" to="1" dur="0.01s" begin="0.1s" fill="freeze"/>
        </text>
        <!-- rest of letters... -->
      </g>
    </svg>

    Add role="img" and a <title> to the <svg>, and wrap the individual letters in <g aria-hidden="true">. That gives screen readers one clean label to read. It works well in some combinations and badly in others, so if the text is critical, don’t animate it.

    Here is the complete code. It’s easier to write it when you have an AI to do it for you:

    CodePen Embed Fallback

    For longer text, a library like GSAP gives you more control, but the same accessibility risks we discussed earlier apply, and the results across screen readers are inconsistent:

    <h1>
      <span class="splitfirst">Todos los hongos son</span>
      <span class="splitlast">mágicos</span>
    </h1>
    const splitFirst = SplitText.create('.splitfirst', {
      type: "chars",
    });
    const splitLast = SplitText.create('.splitlast', {
      type: "chars, lines",
      mask: "lines"
    });
    
    const tween = gsap.timeline()
    .from(splitFirst.chars, {
      xPercent: 100,
      stagger: 0.1,
      opacity: 0,
      duration: 1, 
    })
    .from(splitLast.chars, {
      yPercent: 100,
      stagger: 0.1,
      opacity: 0,
      duration: 1,
    });

    This would be a nice approach for Option B if we had gone that route. See how “serene” things feel as the text fades in.

    CodePen Embed Fallback

    Masking & Clipping

    The clip-path and mask properties allow us to hide portions of an element, but they work on fundamentally different principles. Clipping is a binary decision: pixels are either fully visible or completely gone,  making it the right choice for clean geometric shapes, like polygons, circles, or SVG paths, where the browser can also optimize rendering more efficiently. Masking, on the other hand, uses luminance or alpha channel values: white reveals, black hides, and everything in between produces partial transparency. This makes it the tool for soft edges, gradient fades, and irregular textures. Keep in mind that if you have a very complex vector shape, it might be more performant to use a mask than a vector clip-path. Sarah Drasner has a nice write-up on when it makes sense to use one over the other.

    Our project is a very clear use case for clip-path. We have a circle shape that starts with clip-path: circle(0%), which makes the element invisible (the clipping circle has zero radius). Over the duration of the animation it expands to circle(100%), which fully reveals the element as the circle grows outward from its center. Meanwhile, we fade things in with the help of opacity.

    #rainbow, #floor, #mushroom, #flores {
      opacity: 0;
      animation: maskAnim 2s ease-in forwards;
    }
    
    @keyframes maskAnim {
      0%, 1% { 
        clip-path: circle(0%);
        opacity: 1; 
      }
      100% { 
        clip-path: circle(100%); 
        opacity: 1; 
      }
    }

    Note: The 1% keyframe is there to make sure the browser starts the clip-path interpolation from circle(0%) rather than from whatever value the element might already have. Without it, some browsers will unexpectedly jump at the very start. A cleaner alternative is to use animation-fill-mode: both because it locks the element in its from state before the animation begins.

    From there, we apply the same animation to the different SVG groups in our illustration:

    <g id="rainbow">...</g>
    <g id="floor">...</g>
    <g id="mushroom">...</g>
    <g id="flowers">...</g>

    How psychedelic is this?!

    CodePen Embed Fallback

    Scroll-Driven Animations

    Scroll-driven animations are great because we can connect an animation’s progress to the user’s scrolling instead of a typical timeline that runs and stops.

    We can use it for subtle and somewhat “trippy” movement, like a light parallax effect. In this case, we can make things that appear closer to the user move faster than the ones that are more distant.

    CodePen Embed Fallback

    This is the full CSS:

    #estrellas, #arcoiris, .text-line, #fecha, #arco, #flores, #dir, #piso, #barras {
      animation: moveUp both;
      animation-timeline: view();
    }
    
    @keyframes moveUp {
      from { transform: translateY(var(--offset)); opacity: 0; }
      to { transform: translateY(0); opacity: 1; }
    }
    
    #estrellas { --offset: 10vh; }
    #arcoiris { --offset: 20vh; }
    #fecha { --offset: 45vh; }
    #arco { --offset: 50vh; }
    #dir { --offset: 50vh; }
    #flores { --offset: 65vh; }
    #piso { --offset: 85vh; }
    #barras { --offset: 90vh; }

    The animation-timeline: view() says that things should start the animation as soon as an element enters the scrollport when the user scrolls into it, and fully completes when it scrolls out of view. To make things move at different velocities, we place them at different offsets using an indexed --offset custom property like we did earlier for splitting text.

    3D Transforms

    This one is trickier and we need to keep an eye on performance. A tool like Layoutit can help carry the lift because it has a voxels and terrain generator built entirely with CSS 3D. It can go even further when it’s complemented with VoxCSS, a full voxel engine that renders 3D cuboids using only CSS Grid layers and transforms without the complexity of Canvas or WebGL.

    Let’s put together some combination scrolling and 3D effects. It’s the sort of thing that supports the “hypnotic” and “dancing” ideas in the Option A keyword list. Check this out:

    CodePen Embed Fallback

    Here, I’ve set up a scene with depth using the perspective property and then wrap all the child elements inside the scene in a 3D space with transform-style: preserve-3d. This way, all the child image elements rotate and translate along the depth axis (or z-axis).

    Let’s connect that to a scroll-driven animation that uses transform: rotateY:

    .scene {
      perspective: 1200px;
    }
    
    .img-wrapper { 
      transform-style: preserve-3d; 
      animation: rotateImg linear;
      animation-timeline: scroll();
    
      > img {
        transform: rotateY(270deg) translate3d(0, 50px, var(--distance));
      }
    
      > img:nth-child(2) {
        transform: rotateY(180deg) translate3d(0, 50px, var(--distance));
      }
    }
    
    /* etc. */
    
    @keyframes rotateImg {
      to { transform: rotateY(360deg); }
    }

    Custom Cursors

    cursor might be one of the most unused CSS properties. There are many cursor types we can use, although there are definitely opinions on just how far to go with this.

    And we can use it to play around with the images, displaying different cursors on different containers when the user hovers them. I would personally use an SVG and PNG image for transparency support, though the property supports any raster image.

    It’s worth noting that cursor sizes vary by browser: Firefox caps custom cursors at 32×32px, while Chrome supports up to 128×128px. Most browsers refuse to display — or will downscale — cursors that are larger than 32×32px on high-DPI (retina) screens. Keeping your cursor at 32×32px is the safest choice to ensure consistency.

    For example:

    .box1 {
      cursor: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB0AAAAZCAMAAAD63NUrAAAACVBMVEX///8AAAD///9+749PAAAAAXRSTlMAQObYZgAAAFZJREFUeNqdzksKwDAIAFHH+x+6lIYOVPOhs5OHJnES/5UkYKEkU7xjijSIm50iFh4fAXgYDd/yumVVRSwsqq/nRA3xVK0oo06d5U6DpQZ7PV7lMxH7LkaQAbYFwryzAAAAAElFTkSuQmCC),auto; 
    }

    We can even set multiple fallbacks to ensure the widest level of browser support:

    body {
      cursor: url('path-to-image.png'), url('path-to-image-2.svg'), url('path-to-image-3.jpeg'), auto;
    }

    While this is cool and all, we have to keep accessibility in mind for something that changes default web behavior like this. Custom cursors could be fun to apply to very specific elements rather than wholesale across the board.

    CodePen Embed Fallback

    Bonus: Anchor Positioning

    One more thing before we wrap up. I’ve been playing with CSS Anchor Positioning, inspired by a Kevin Powell demo. We can use it to attach a single pseudo-element to a currently-hovered item instead of attaching a pseudo-element for each and every item. In other words, we create a single element and anchor it to a hovered element, like highlighting cards:

    CodePen Embed Fallback

    That opens up interesting possibilities, like being able to transition the hover state between cards. In this case, I’m using the linear() function to get that natural bounce with help from Easing Wizard.

    Conclusion

    The technical barriers for creating memorable web experiences are mostly gone now. I hope everything we’ve covered here gives you an idea of just how far we can go with modern CSS features that completely remove the need for additional JavaScript. We have more possibilities than ever before, all without the need for complex technical overhead like days past.

    So, instead of asking, is this possible?, the most important question becomes, does this movement tell a better story? If yes, ship it. Use these tools not because you can, but because they help you tell a better story, one that is also accessible and performant.

    And, of course, everything in here is just a handful of ways to do that. But what sort of memorable experiences have you used in your work? Or what have you seen on other sites?


    Creating Memorable Web Experiences: A Modern CSS Toolkit originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-08 13:00
    ↗

    I've said one and mean another, and I've used one when I needed another. Comparing scroll-driven animations, scroll-triggered animations, container query scroll states, and view transitions for my future self. Scroll-Driven, Scroll-Triggered, Scroll States, and View...

    I’ve said one and meant another, and I’ve used one when I needed another. Please bear with me as I note the high-level similarities and differences between scroll-driven animations, scroll-triggered animations, container query scroll states, and view transitions for my future self.

    Scroll-Driven Animations

    A scroll-driven animation is an animation that responds to, yeah, scrolling. Specifically, there’s a direct link between scrolling progress and the animation’s progress. Scroll forwards, the animation moves forward. Scroll backwards, the animation runs backwards. Stop scrolling, the animations stops.

    .element {
      animation: grow-progress linear forwards;
      animation-timeline: scroll();
    }
    CodePen Embed Fallback

    Scroll-Triggered Animations

    A scroll-triggered animation executes on scroll and runs in its entirety. In other words, there’s no direct link with the scroll progress here. When an element crosses some defined threshold — called the trigger activation range — the animation runs, runs, runs. For example, when that element enters and exits the scrollport.

    CodePen Embed Fallback

    Container Query Scroll State

    This one’s in the working draft of CSS Conditional Rules Module Level 5 specification. Here’s how the spec defines it:

    […] allows querying a container for state that depends on scroll position. 

    This is why my brain hurts so much. It’s sorta like a scroll-driven animation, sorta like a scroll-triggered animation, but updates styles when a container reaches some sort of scroll condition, say:

    .sticky-nav {
      container-type: scroll-state;
      position: sticky;
      top: 0;
    
      @container scroll-state(stuck: top) {
        background: orangered;
        border-radius: 0;
        flex-direction: row;
        width: 100%;
    
        a {
          text-decoration: none;
        }
      }
    }
    CodePen Embed Fallback

    View Transition

    This has nothing to do with scroll! And it has nothing to do with view(). We’re actually talking about a complete API with interlocking CSS and JavaScript features that can do two things:

    Same-document transitions

    An element changes from one state to another in response to a user interaction. I was really tickled by this one from Modern Web Weekly animating radio button check states where the state moves from one input to the other.

    CodePen Embed Fallback

    Basically, the state changes on the same page it started. Bramus is king of all-thing view transitions with oodles of beautiful examples in this collection from the Chrome team.

    Cross-document transitions

    Animating from one page to the next. The default usage is a crossfade from Page A to Page B (and back again) and is really easy to implement. It can get much more complex from there, of course. Sunkanmi recently shared several recipes, like this neat one that wipes out the first page with a circular clip-path revealing the second page.

    That’s all!

    It helps me to spell things out like this.

    TypeWhat it does
    Scroll-Driven AnimationsScroll forwards, the animation moves forward. Scroll backwards, the animation runs backwards. Stop scrolling, the animations stops.
    Scroll-Triggered AnimationsWhen an element crosses some defined threshold — called the trigger activation range — the animation runs, runs, runs.
    Container Query Scroll StateUpdates styles when a container reaches some sort of scroll condition.
    View TransitionAPI for same-document transitions (element changes from one state to another on the page) and cross-document transitions (transitioning from one page to the next, and back).

    Scroll-Driven, Scroll-Triggered, Scroll States, and View Transitions originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-04 13:14
    ↗

    We dive again into CSS Pie Charts! This time, Author Antoine Villepreux delivers semantic and flexible charts without a single line of JS. Another Stab at the Perfect CSS Pie Chart… Sans JavaScript! originally handwritten and published with love on CSS-Tricks. You should...

    Recently, Juan Diego Rodríguez published an excellent article exploring how far CSS can be pushed to build a semantic and customizable pie chart while keeping JavaScript to a minimum.

    Citing Juan himself:

    In this article, we’ll try making the perfect pie chart in CSS. That means avoiding as much JavaScript as possible while addressing major headaches that comes with handwriting pie charts.

    And it stated some goals that I want to go through again in order of priority:

    • This must be semantic! Meaning a screen reader should be able to understand the data shown in the pie chart.

    To my understanding, the original article’s solution reached that goal. Its semantic approach (labels in plain HTML + values as attributes reinjected into the DOM via pseudo-elements) is clean, expressive, and hopefully accessible.

    • This should be HTML-customizable! Once the CSS is done, we only have to change the markup to customize the pie chart.

    The original article reached that goal as well.

    • This should keep JavaScript to a minimum! No problem with JavaScript in general, it’s just more fun this way.

    The original article aimed to use as little JavaScript as possible, mainly for fun. I tend to disagree slightly. For me, it should not be just for fun, since…

    • JavaScript is there to deal with states and logic, and
    • CSS is there to style the markup.

    The initial “no JavaScript” constraint was meaningful to me. CSS should be powerful enough to let us style a pie chart. JavaScript should not be required. So, I decided to see whether there was a way to 100% get rid of it and, for fun, forked the article’s CodePen during a lunch break.

    I kept the original code as unchanged as possible, preserving its semantic approach and HTML-side customizability. If It Ain’t Broke, Don’t Fix It™.

    Coincidentally, this article came right after a recent short pen of mine toying with bar charts. So I was already in the mood for charts. But bar charts are far easier: each bar’s position or size does not depend on the others. A pie chart is a different beast: each slice’s position depends on the previous one. Luckily, this made it more of a fun challenge.

    But before diving into my take on pie charts, let’s see how these have been approached by other web developers.

    Prior Art

    I read many blogs, articles, and code examples from professional front-end developers, but I am not one myself, so I am not entirely certain of my ability to identify the most relevant and up-to-date prior art… Let’s try anyway.

    It is easy to find many JavaScript libraries dealing with charts. I have used them a lot in my work. However, due to our no-JavaScript constraint, we shall exclude them.

    I started looking for CSS-only pie charts, and one of the first libraries that pops up is Chart-CSS. It advertises semantic structure, HTML tags to display data, accessibility, and raw data inside the markup. It seems to be a very good library and does not use any JavaScript.

    Instead, it uses HTML tables, which, in my opinion and experience, makes total sense (most of the time, source data comes in a table). However, it does not solve the specific challenge of letting the user set only the values while having the start and end angles of each slice automatically computed. In this case, users still have to manually define them.

    There are also very good articles discussing charts or data visualization in general. To name a few:

    • Vitaly Friedman’s “2022 Guide to Accessible Front-End Components” is still relevant.
    • Sarah L. Fossheim wrote extensively about data visualization accessibility between 2020 and 2024

    They just have one small (but very important to us) drawback. While these resources are valuable in explaining how chart accessibility should work, they do not really address easy HTML “interface” nor pure CSS implementations.

    How I Tackled the Problem

    If you are still reading, I assume you are at least somewhat interested in my approach. Understandably, If you just want to see the code, here it is!

    CodePen Embed Fallback

    Initially, the reason JavaScript was required was that each slice needed to know the value of the previous one. However, due to how CSS property inheritance works, a child cannot know the state of another child. Despite knowing this, I first tried to determine whether there were niche or “voodoo” techniques that would allow me to keep the original HTML markup and attribute-based approach while removing JavaScript.

    I know that people like Roman Komarov can do incredible things with CSS, so I even considered exploring techniques involving property animations. But I clearly did not have the time to investigate that direction.

    I returned to the core issue: because of how CSS inheritance works, children cannot know the state of their siblings. I obviously needed a “surrounding entity” to handle this.

    In Juan’s post, that “entity” was JavaScript, which could loop through all children and compute the appropriate slice accumulations.

    const pieChartItems = document.querySelectorAll(".pie-chart li");
    
    let accum = 0;
    
    pieChartItems.forEach((item) => {
      item.style.setProperty("--accum", accum);
      accum += parseFloat(item.getAttribute("data-percentage"));
    });

    The JavaScript code sets an --accum value for each slice, which holds the percentage values of all charts prior to it. Without it, we wouldn’t know where to position each slice and its corresponding label.

    In HTML/CSS, that entity exists too: the classic parent element. Therefore, my solution was to move the percentage values to the parent.

    First, let’s remember what the original markup for the pie chart looked like this:

    <ul class="pie-chart">
      <li data-percentage-1="10">Apple</li>
      <li data-percentage-2="30">Banana</li>
      <li data-percentage-3="20">Orange</li>
      <li data-percentage-4="40">Strawberry</li>
    </ul>

    While the version we’ll be using looks like this:

    <ul class="pie-chart" data-percentage-1="10" data-percentage-2="30" data-percentage-3="20" data-percentage-4="40">
      <li>Apple</li>
      <li>Banana</li>
      <li>Orange</li>
      <li>Strawberry</li>
    </ul>

    We’ve moved all values to the parent <ul> and given each item a dedicated name — effectively indexing them.

    I had previously experimented with this kind of “indexing” CSS workaround, for example, to compensate for the lack of sibling-index() and sibling-count() functions to generate random numbers. I knew this was the right direction and that the rest would follow logically on the CSS side.

    Spoiler: sibling-index() and sibling-count() are becoming Baseline soon!

    It may look like duplication since we didn’t add anything but rather moved the attributes. However, this slight change allows us to manage all labels and values from the parent in CSS. What’s best, we still keep all attributes close together. And while you may say that this won’t scale as well, if we have data with tons of entries, then a pie chart is rarely the best choice to show it.

    Optionally, we could add data-label attributes to the labels just to pair labels and values visually.

    <ul class="pie-chart" data-percentage-1="10" data-percentage-2="30" data-percentage-3="20" data-percentage-4="40">
      <!-- Optional data-label attributes: just visual hints-->
      <li data-label-1>Apple</li>
      <li data-label-2>Banana</li>
      <li data-label-3>Orange</li>
      <li data-label-4>Strawberry</li>
    </ul>

    Now let’s examine the CSS. The implementation requires two sets of some repetitive but straightforward CSS rules.

    Firstly, we’ll need to pass down each percentage to its corresponding slice. To do so, we use Juan’s and get the data-percentage attributes into CSS through the upgraded attr() function. In parallel, we’ll assign them to the corresponding slice using the nth-child() selector.

    .pie-chart {
       /* We write one for each slice we think we'll need */
      --p-100-1: attr(data-percentage-1 type(<number>)); :nth-child(1) { --p-100: var(--p-100-1) }
      --p-100-2: attr(data-percentage-2 type(<number>)); :nth-child(2) { --p-100: var(--p-100-2) }
      --p-100-3: attr(data-percentage-3 type(<number>)); :nth-child(3) { --p-100: var(--p-100-3) }
      --p-100-4: attr(data-percentage-4 type(<number>)); :nth-child(4) { --p-100: var(--p-100-4) }
       /*...*/
    }

    For that kind of repetitive/incremental code, I keep it as a one-liner without carriage return. IMHO it’s a very acceptable exception to common formatting rules as it prevents typos by easing scan-ability of and also eases further iterations (e.g., adding support for more slices). But your mileage may vary.

    Let’s look a little closer at what’s going on here. At the level of the whole pie, we access the percentages for each slice through their index and store them in a corresponding CSS variable, so the fourth element gets --p-100-4, the fifth element gets --p-100-5, and so on:

    --p-100-4: attr(data-percentage-4 type(<number>));

    Next, we pass each a --p-100 variable that’s local to each slice.

    :nth-child(4) {
      --p-100: var(--p-100-4);
    }

    We now have all these slice values accessible at two levels:

    • On the pie, via indexed variables: --p-100-1, --p-100-2, --p-100-3
    • On each slice, via the --p-100 variable

    Now, we’ll need to calculate the corresponding --accum value, which is the sum of the values of all previous slices. To do so, we’ll have to progressively sum each percentage after each slice, then assign the value to the slice using nth-child() again.

    .pie-chart {
      /* ... */
      --accum-1: 0;                                     :nth-child(1) { --accum: var(--accum-1) }
      --accum-2: calc(var(--accum-1) + var(--p-100-1)); :nth-child(2) { --accum: var(--accum-2) }
      --accum-3: calc(var(--accum-2) + var(--p-100-2)); :nth-child(3) { --accum: var(--accum-3) }
      --accum-4: calc(var(--accum-3) + var(--p-100-3)); :nth-child(4) { --accum: var(--accum-4) }
      /*...*/
    }

    Again, we first work at the pie level, where we compute one dedicated variable per slice. The first slice is a special case: there is no previous slice, so the accumulation is 0. While in the rest, the accumulation for the slice n is the accumulation of the slices before n−1 plus the value of the slice n−1.

    --accum-4: calc(var(--accum-3) + var(--p-100-3));

    The fourth element gets --accum-4, the fifth element gets --accum-5, and so on. Just as the percentages, at the level of each slice, we assign them to the local variable --accum.

    :nth-child(4) {
      --accum: var(--accum-4);
    }

    Once again, we have all these slice accumulation values accessible at two levels:

    • On the pie, via indexed variables: --accum-1, --accum-2, --accum-3
    • On each slice, via the --accum variable

    I hope future native CSS features (perhaps @function?) will prevent us from having to resort to such repetitive code. In the meantime, this can be simplified with a CSS preprocessor (Sass, Less).

    While forking the original Pen, some questions popped out in my mind — that I did not actually explore — to keep the original code as unchanged as possible:

    • What about using <label> and <meter> for labels and values?
    • What about using a <table> (since charts are often extracted from tables with rows like [label, value])?

    Note About Accessibility

    In my fork, I handled accessibility the same way Juan did, but with one slight modification: I used counter-reset / counter() instead of attr() to assign the percentages to the content property. This should work just as good as attr(), but let’s make sure it is still screenreader-friendly:

    Another thing I thought of changing was the label elements inside each <li>. In the original article, Juan uses a <strong> element, while I opted for <span> instead. However, I think it may be totally acceptable to use the <label> itself. We normally think of them as being bounded inside <form> elements, but the spec says that we could expect to use them in contexts “where phrasing content is expected.” So I could not find any obligation to use them only in the context of forms.

    Default Colors

    Juan’s article also called upon some improvements, which I tried to address in my fork:

    • data-color can be omitted, and colors are then generated.
    • Colors can be defined either on the parent or on the children (user’s choice; both are supported).

    This translates to the next snippet for each slice:

    .pie-chart li {
      --color: attr(data-color type(<color>));
      --bg-color: var(--color, hsl(calc(360deg * sibling-index() / sibling-count()) 90% 40%));
    }

    I refrained from using sibling-index() and sibling-count() in the main part, since they aren’t Baseline (yet, but soon!), but I couldn’t hold myself back since calculating the color hue is so much fancier with them. These functions really allow some magic!

    Still, here is my “CSS-only polyfill”; repetitive (yet simple) code:

    .pie-chart {
      :has(:nth-child(1)) { --sibling-count: 1 } :nth-child(1) { --sibling-index: 1; }
      :has(:nth-child(2)) { --sibling-count: 2 } :nth-child(2) { --sibling-index: 2; }
      :has(:nth-child(3)) { --sibling-count: 3 } :nth-child(3) { --sibling-index: 3; }
      :has(:nth-child(4)) { --sibling-count: 4 } :nth-child(4) { --sibling-index: 4; }
      /* ... */
    }

    More Chart Types?

    We now have a common foundation for other chart types. As a proof of concept, I implemented a bar chart mode in my fork.

    CodePen Embed Fallback

    A Web Component, Perhaps?

    In a way, we already have a web component here — one without JavaScript, using light DOM.

    And to me <pie-char attributes...> is not fundamentally different that either <div class="pie chart" attributes...> or <div pie chart attributes...>. I can see value in this approach when considering progressive enhancement, though.

    For example, a chart that refreshes automatically and fetches live data. But that would require JavaScript — which we are deliberately avoiding today.


    Another Stab at the Perfect CSS Pie Chart… Sans JavaScript! originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-03 15:02
    ↗

    The offset-path property in CSS defines a movement path for an element to follow during animation. This property began life as motion-path. This, and all other related motion-* properties, are being renamed offset-* in the spec. We’re changing … offset-path originally...

    The offset-path property in CSS defines a movement path for an element to follow during animation.

    This property began life as motion-path. This, and all other related motion-* properties, are being renamed offset-* in the spec. We’re changing the names here in the almanac. If you want to use it right now, probably best to use both syntaxes.

    Here’s an example using the SVG path syntax:

    .thing-that-moves {
      /* "Old" syntax. Available in Blink browsers as of ~October 2015 */
      motion-path: path("M 5 5 m -4, 0 a 4,4 0 1,0 8,0 a 4,4 0 1,0 -8,0");
     
      /* Currently spec'd syntax. Should be in stable Chrome as of ~December 2016 */
      offset-path: path("M 5 5 m -4, 0 a 4,4 0 1,0 8,0 a 4,4 0 1,0 -8,0");
    }

    This property cannot be animated, rather it defines the path for animation. We use the offset-path property to create the animation. Here’s a simple example of animating motion-offset with a @keyframes animation:

    .thing-that-moves {
      offset-path: path('M 5 5 m -4, 0 a 4,4 0 1,0 8,0 a 4,4 0 1,0 -8,0');
      animation: move 3s linear infinite;
    }
    
    @keyframes move {
      100% { 
        motion-offset: 100%;   /* Old */
        offset-distance: 100%; /* New */
      }
    }
    CodePen Embed Fallback

    In this demo, the orange circle is being animated along the offset-path we set in CSS. We actually drew that path in SVG with the exact same path() data, but that’s not necessary to get the motion.

    Say we drew a funky path like this in some SVG editing software:

    We would find a path like:

    The d attribute value is what we’re after, and we can move it straight to CSS and use it as the offset-path:

    CodePen Embed Fallback

    Note the unitless values in the path syntax. If you’re applying the CSS to an element within SVG, those coordinate values will use the coordinate system set up within that SVG’s viewBox. If you’re applying the motion to some other HTML element, those values will be pixels.

    Also note we used a graphic of a finger pointing to show how the element is automatically rotated so it kinda faces forward. You can control that with offset-rotate:

    .mover {
      offset-rotate: auto; /* default, faces forward */
      offset-rotate: reverse; /* faces backward */
      offset-rotate: 30deg; /* set angle */
      offset-rotate: auto 30deg; /* combine auto behavior with a set rotation */
    }

    Values

    As best as we can tell, path() and none are the only working values for offset-path.

    The offset-path property is supposed to accept all the following values.

    • path(): Specifies a path in the SVG coordinates syntax
    • shape(): Creates a path with CSS-y commands instead of SVG
    • url(): References the ID of an SVG element to be used as a movement path
    • none: Specifies no offset path at all
    • Shape functions: A set of CSS functions that specify a shape in accordance to the CSS Shapes specification, which includes:
      • circle()
      • ellipse()
      • inset()
      • path()
      • polygon()
      • shape()
      • xyzh()

    Here’s some tests:

    CodePen Embed Fallback

    Even telling an SVG element to reference a path definied the same SVG via url() doesn’t seem to work.

    With the Web Animations API

    Dan Wilson explored some of this in Future Use: CSS Motion Paths. You have access to all this same stuff in JavaScript through the Web Animations API. For example, say you’ve defined a offset-path in CSS, you can still control the animation through JavaScript:

    CodePen Embed Fallback

    More Examples

    Heads up! A lot of these were created before the change from motion-* naming to offset-*. Should be pretty easy to fix them if you’re so inclined.

    CodePen Embed Fallback
    CodePen Embed Fallback
    CodePen Embed Fallback
    CodePen Embed Fallback
    CodePen Embed Fallback
    CodePen Embed Fallback
    CodePen Embed Fallback

    Browser support

    Is There Another Way to Do This?

    Our own Sarah Drasner wrote about SMIL, SVG’s native method for animations, and how animateMotion is used to animate objects along a SVG path. It looks like:

    GreenSock is another way though. Sarah talks about this in GSAP + SVG for Power Users: Motion Along A Path (SVG not required). Example:

    CodePen Embed Fallback

    Related Properties

    clip clip-path
    Almanac on Sep 5, 2011

    clip-path

    .element { clip: rect(110px, 160px, 170px, 60px); }
    Sara Cope
    offset-path
    Almanac on May 4, 2018

    offset-anchor

    .element { offset-anchor: right top; }
    Geoff Graham
    Almanac on Jul 22, 2016

    offset-distance

    .element { offset-distance: 50%; }
    Geoff Graham
    offset offset-rotate
    Almanac on

    offset-rotate

    .element { offset-rotate: 30deg; }
    Chris Coyier
    Almanac on Jul 9, 2025

    circle()

    .shape { clip-path: circle(100px); }
    John Rhea
    Almanac on

    ellipse()

    .shape { clip-path: ellipse(60px 40px); }
    John Rhea
    Almanac on Jul 15, 2025

    inset()

    .element { clip-path: inset(10px 2em 30% 3vw); }
    John Rhea
    Almanac on Jun 18, 2025

    path()

    .element { clip-path: path("…"); }
    John Rhea
    Almanac on Jul 24, 2025

    polygon()

    .element { clip-path: polygon(50% 0%, 75% 6.7%, 93.3% 25%, 100% 50%, 93.3% 75%, 75% 93.3%, 50% 100%, 25% 93.3%, 6.7% 75%, 0% 50%, 6.7% 25%, 25% 6.7%); }
    John Rhea
    Almanac on Jun 10, 2025

    shape()

    .triangle { clip-path: shape(from 50% 0%, line by 50% 100%, hline to 0%, line to 50% 0%, close); }
    John Rhea
    Almanac on Aug 14, 2025

    url()

    .element { background-image: url("https://example.com/image.png"); }
    Gabriel Shoyombo
    Almanac on Jul 15, 2025

    xywh()

    .element { clip-path: xywh(60px 4em 50% 10vw round 10px 30px); }
    John Rhea

    offset-path originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-03 13:03
    ↗

    The CSS @custom-media at-rule allows creating aliases for media queries. @custom-media originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

    The CSS @custom-media at-rule allows creating aliases for media queries. This is particularly valuable if you have long or complex media queries that you use multiple times across your codebase. The feature is similar in nature to a media query version of CSS custom properties (CSS variables).

    Syntax

    The syntax for defining an alias is:

    @custom-media (<dashed-ident>) [<media-query-list> | true | false ];

    For example:

    @custom-media --modern-touch (pointer: coarse) and (min-width: 1024px);

    …where the dashed ident is --modern-touch.

    The syntax for using an alias is the same as using any media query, but instead of providing media types or media features, you provide the <dashed-ident> of your defined @custom-media:

    @cutom-media <dashed-ident> {
      /* ... */
    }

    Arguments and Descriptors

    • <dashed-ident>: A user-defined identifier that must start with two dashes (--), similar to functions or custom properties. Just like custom properties, the name is case-sensitive. For example, --mobile-breakpoint and --Mobile-Breakpoint would refer to different custom media definitions.
    • <media-query-list>: A list of media queries, separated by operators.
    • true/false: Always-match / never-match toggles.

    Let’s look at how these work in different contexts, such as how they’re scoped, using them with booleans, defining complex logic, setting rules with the CSS range syntax, and even nesting aliases.

    Scope and Placement

    Unlike custom properties, which are scoped to the element they are defined on (and their children), @custom-media rules are global. They are evaluated in the global scope of the stylesheet and will always apply to the entire document. If multiple @custom-media rules are defined with the same name, the one in scope at the time of evaluation is the one that is used.

    When a @media rule uses a custom alias, i.e. the dashed ident, it looks at the current definition of that alias at that point in the stylesheet. If the alias is redefined later, it does not “update” the media queries that were already processed. For example, in this case margin-block: 1rem will only be applied to body if it is fullscreen and not browser despite the later declaration using the same name.

    @custom-media --screen-display (display-mode: fullscreen);
    
    @media (--screen-display) {
      body {
        margin-block: 1rem;
      }
    }
    
    @custom-media --screen-display (display-mode: browser);

    Note: This scoping behavior is still being discussed and is subject to change in the future.

    Boolean Constants

    In the Syntax section above, note that a @custom-media rule can be explicitly set to true or false. This is useful for “toggling” entire blocks of CSS during development or for feature flagging.

    Operators and Complex Logic

    As @custom-media utilizes the exact same logical operators (and, ,, or, not, only) and grouping rules as @media, you can build complex, parentheses-grouped logic just as you normally would. For a full breakdown of how to use operators, negate features, or hide stylesheets from older browsers, reference the Logic and Operators section of the @media almanac. It is also worth referencing the section on nesting and complex decision-making when building complex queries.

    To, for example, construct a query using the and logical operator, you can write this:

    @custom-media --modern-touch (pointer: coarse) and (min-width: 1024px);

    Range Syntax

    The same as any other <media-query-list>, @custom-media has support for the ranged media query syntax which uses operators, e.g. greater than (>), less than (<), and equals (=), to evaluate conditions:

    /* Old way */
    @custom-media --tablet (min-width: 768px) and (max-width: 1024px);
    
    /* New, cleaner way */
    @custom-media --tablet (768px <= width <= 1024px);

    Nested Aliases

    One unique feature of @custom-media aliases is that they can reference each other. This allows you to build layered, semantic conditions:

    @custom-media --narrow-window (width < 30rem);
    @custom-media --small-and-hover (--narrow-window) and (hover: hover);
    
    @media (--small-and-hover) {
      /* Styles for mobile-sized screens with hover capabilities */
    }

    However, if a loop is detected, all involved custom media queries are treated as undefined. For instance, if --query-a references --query-b, then --query-b cannot reference --query-a. Similarly, a custom media query cannot refer to itself.

    Also be aware of over-nesting, as that can make debugging and identifying which layer of query is having the relevant impact in your browser’s developer tools very difficult.

    Example: Defining Common Breakpoints

    Instead of remembering if your “tablet” breakpoint is 768px or 800px, you can define it once at the top of your stylesheet.

    @custom-media --tablet (min-width: 768px);
    
    .sidebar {
      display: none;
    
      @media (--tablet) {
        display: block;
      }
    }

    Example: Defining Shorthands for Existing Properties

    Standard boilerplate such as (prefers-reduced-motion: reduce) can be used many times across a codebase, and those bytes add up. You can use @custom-media to define simpler alternatives:

    @custom-media --prefers-reduced-motion (prefers-reduced-motion: reduce);
    
    @media (--prefers-reduced-motion) {
      /* ... */
    }
    @custom-media --js-enabled (scripting: enabled);
    @custom-media --js-disabled (scripting: none);
    
    @media (--js-disabled) {
      .no-js-banner {
        display: block;
      }
    }

    There are a great number of Open Props @custom-media Recipes you may consider using.

    JavaScript Support

    @custom-media aliases are not exposed to the JavaScript matchMedia() method, meaning this code will not work, even if you have the alias defined somewhere on your page.

    matchMedia("(--tablet)")

    Specification

    The @custom-media at-rule is defined in the Media Queries Level 5 specification.

    Browser Support

    Unsupported browsers largely ignore @custom-media, so fallback declarations and progressive enhancement strategies can be advantageous. You can use @supports to check if @custom-media is supported in the user’s browser, like so:

    @supports (at-rule(@custom-media)) {
      /* ... */
    }

    Ironically, however, at time of writing, the @supports at-rule evaluation functionality doesn’t have full support across browsers (Chrome 148+ only), so you will need to check if it is supported in your case. You can see the discussion on this in CSS Drafts Issue #2463.

    Another approach is to use a tool such as PostCSS Custom Media, which will expand the rules in a build step to achieve wider browser support.


    @custom-media originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-03 13:02
    ↗

    The @function at-rule defines CSS custom functions. These custom functions are reusable blocks of CSS that can accept arguments, contain complex logic, and return values based on that logic. @function originally handwritten and published with love on CSS-Tricks. You should...

    The @function at-rule defines CSS custom functions. These custom functions are reusable blocks of CSS that can accept arguments, contain complex logic, and return values based on that logic. The feature is similar in nature to a more dynamic version of custom properties (CSS variables).

    Note: There is also a @function at-rule in Sass which is similar in purpose but different in function to the native CSS @function. Be aware of this if Sass is part of your stack or when searching for resources as it is easy to conflate one with the other.

    Syntax

    The @function at-rule defines a custom function, using the following syntax:

    @function --function-name(<function-parameter>#?) [returns <css-type>]? {
      <declaration-rule-list>
    }
    
    <function-parameter> = <custom-property-name> <css-type>? [ : <default-value> ]?

    In other words, we define the function’s name as a dashed ident (--my-function), supply some condition we want to match (<function-parameter>), and say what sort of thing we want to return, say, a CSS[<length>] value. And, if that condition matches, we apply styles (<declaration-rule-list>).

    Let’s dig deeper into what those things actually mean.

    Arguments and Descriptors

    There are a number of parts to the syntax for @function to handle different parts of the feature. It may all look very complex — and it is — but it’ll become clearer later when we look at some examples.

    --function-token

    A user-defined identifier that must start with two dashes (--), similar to the dashed-ident of custom properties. Just like custom properties, the name is case-sensitive. For example, --conversion and --Conversion would refer to different custom function definitions.

    @function --progression()

    <function-parameter> (optional)

    An optional comma-separated list of inputs that can include:

    • --param-name: The name of the argument (must start with --).
    • <css-type> (optional): A keyword or type (e.g., <length>, <color>) that tells the function what sort of input or result it’s returning when it hits a matched condition.
    • <default-value> (optional): A fallback value that’s returned if the result is invalid, such as the argument is omitted during the function call. If you provide a default value, it must be valid to the aforementioned <css-type> (e.g. a <length> must default to a valid CSS length). It is separated from the rest of the parameter definition with a colon (:).
    • returns <css-type> (optional): Defines the expected output type of the function. This helps the browser validate logic before rendering. If a type isn’t specified then, anything will be valid (like writing returns type(*)).
    • <declaration-rule-list>: CSS declarations and at-rules that construct the function’s body and logic. It can include custom properties and the result descriptor — either at the root or nested within an at-rule.
    @function --progression(--current <number>, --total <number>) returns <percentage> {
      result:
    }

    The result descriptor that defines what the custom function will return. If a custom function forgoes the result descriptor, it will always return guaranteed-invalid value, just like a broken custom property.

    @function --progression(--current <number>, --total <number>) returns <percentage> {}

    Basic Usage

    For an example of the most basic function you could make, we have a function that calculates a provided value (e.g. 20px) in half (e.g. 10px), and returns returns it as a length unit (e.g. px):

    @function --half(--size <length>) {
      result: calc(var(--size) / 2);
    }

    Here, we are ‘naming’ our function by setting the function-token to --half. We are then creating a function-parameter called --size, and setting the css-type to <length>, so that it will only accept length values. The result descriptor is set to calc(--size / 2), which uses the CSS Calculating Function to halve the value sourced from the size function-parameter.

    We then use the function like so:

    .container {
      margin-inline: --half(20px); /* This will resolve to 10px */
    }

    Type Checking

    Just like when writing JavaScript or other languages, sometimes we want to ensure a function only accepts certain arguments. For example, what if we want to ensure that only numbers can be input and that only a percentage can be output?

    @function --progression(--current <number>, --total <number>) returns <percentage> {
      result: calc(var(--current) / var(--total) * 100%);
    }
    
    .progress-bar {
      width: --progression(3, 5); /* Evaluates to 60% */
    }

    The <css-type> is enclosed in angle brackets in a manner identical to how you type-check a custom property via @property. If an argument does not match the declared type (e.g. <color>), the function call becomes invalid, which is very valuable for catching bugs early in large codebases.

    You can use a <syntax-combinator> to allow multiple types by wrapping the types in type() and using | as a separator. For example, --alpha here allows both <number> and <percentage>:

    @function --transparent(--color <color>, --alpha type(<number> | <percentage>));

    Comma-Separated Lists

    CSS uses commas to separate the inputs of a custom function, which begs the question: what if you wish to provide a list of values? To provide a list of values as one input rather than several separate inputs, you must first mark a function to expect a list.

    To do this, you suffix the # character to the <css-type>. When calling the function, you then wrap the list of values in curly braces, which tells the browser to treat everything inside the braces as a single argument.

    For instance:

    /* Calculates the distance between the highest and lowest values in a list, plus another input */
    @function --get-range(--list <length>#, --n <length>) {
      result: calc(max(var(--list)) - min(var(--list)) + var(--n));
    }
    
    div {
      /* Finds the difference between 10px and 100px, then adds 200px */
      padding-block: --get-range({10px, 100px, 50px, 25px}, 200px); /* 290px */
    }

    Constructs and the CSS Cascade

    The result descriptor follows the rules of the CSS Cascade. That means you can declare multiple result values, and the last valid matching value will win, just like any other properties. As such, conditional group rules (@media, @container, @supports) and other functions, such as if(), provide a lot of additional possibilities.

    In this case, we return a --suitable-font-size that defaults to 16px when the screen is less than 1000px pixels. If the screen is greater than 1000px then the “winning” style is what’s in the @media block.

    @function --suitable-font-size() returns <length> {
      result: 16px;
    
      @media (width > 1000px) {
        result: 20px;
      }
    }
    
    body {
      font-size: --suitable-font-size();
    }

    Keep in mind that the last defined value always wins, so if you were to write the example below, the result would always be 16px, regardless of the media query being triggered.

    @function --suitable-font-size() returns <length> {
      @media (width > 1000px) {
        result: 20px;
      }
    
      result: 16px;
    }

    The adherence to the established cascade also allows you to use custom properties within a function. These custom properties are locally scoped, so they are only accessible in your custom function and any custom function that references it and thus won’t unexpectedly leak out globally and interact with the rest of your CSS.

    @function --spacing-scale(--multiplier) {
      --base-unit: 8px;
      result: calc(var(--base-unit) * var(--multiplier));
    }

    You can also use other custom functions within a custom function, essentially nesting one function within another. This allows for very clean code, where each section only does one job and functions can be widely reused.

    @function --square(--n) {
      result: calc(var(--n) * var(--n));
    }
    
    @function --circle-area(--radius) {
      --pi: 3.14159;
      result: calc(var(--pi) * --square(var(--radius)));
    }
    
    .blob {
      width: calc(--circle-area(10) * 1px); /* 314.159px */
    }

    Defaults

    Functions can handle multiple arguments and provide default values. The default value is defined by including it at the end of the function parameter, separated by a colon (:).

    /* Define the function */
    @function --brand-glass(--opacity <number>: 0.5) returns <color> {
      result: rgb(10 120 255 / var(--opacity));
    }
    
    /* Use the function */
    .header {
      background: --brand-glass(); /* Defaults to 0.5 */
    }
    
    .header:hover {
      background: --brand-glass(0.8); /* Overrides to 0.8 */
    }

    No Side Effects

    A CSS @function can only return a value; it cannot do anything else. For example, you cannot change a property inside of a function or use a function to generate multiple declarations. For such abilities, one must look to the proposed @mixin at-rule, which would provide functionality in this manner, allowing multiple lines of CSS properties and other complex logic.

    Circular Dependencies

    CSS is very strict about circular logic. If Function A calls Function B, and Function B calls Function A, the browser will catch this cyclic dependency and immediately mark both as invalid.

    This also applies to CSS Custom Properties and referring to the custom function itself. If a function relies on a custom property or function that is itself calculated by that same function, the browser will end the calculation to prevent an infinite recursion.

    Specification

    The @function at-rule is defined in the CSS Custom Functions and Mixins Module Level 1 specification.

    Browser Support

    Unsupported browsers ignore @function, so fallback declarations and progressive enhancement strategies can be advantageous. You can use @supports to check if @function is supported in the user’s browser, like so:

    @supports (at-rule(@function)) {
      /* ... */
    }

    Ironically, however, at time of writing, the @supports at-rule evaluation functionality doesn’t have full support across browsers (Chrome 148+ only), so you will need to check if it is supported in your case. You can see the discussion on this in CSS Drafts Issue #2463.

    More Information

    • Functions in CSS?!
    • CSS Custom Functions are coming … and they are going to be a game changer!

    @function originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-02 12:59
    ↗

    The CSS ::search-text pseudo-element selects the matching text from your browser's "find in page" feature. ::search-text originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

    The CSS ::search-text pseudo-element selects matching text from your browser’s “find in page” feature. For example, if you use your browser search to find “search-text” on this page, all instances of it will highlight. This pseudo-element lets us style the appearance of that highlight.

    And a bonus! If there are multiple matches on the page, then ::search-text can be used with the :current pseudo-class to style the match that’s currently in focus.

    You can “find in page” using the CTRL + F (for Windows) or "⌘F" (for Mac) keyboard shortcuts.

    ::search-text {
      background: oklch(87% 0.17 90) /* yellow */;
      color: black;
    }
    
    ::search-text:current {
      background: oklch(62% 0.22 38) /* red */;
      color: white;
    }
    CodePen Embed Fallback

    The CSS ::search-text pseudo-element is defined in the CSS Pseudo-Elements Module Level 4 specification.

    Syntax

    Pretty straightforward! Declare the pseudo-element and add your style rules:

    <element-selector>::search-text{
      /* ... */
    }

    Usage

    It’s typically declared by itself (::search-text), but can be appended to specific elements as well:

    /* All text */
    ::search-text {}
    html::search-text {} /* kind of redundant */
    /* Specific element */
    section::search-text {}
    strong::search-text {}

    We’re a little limited as far as what CSS properties we can declare in ::search-text. Here is what it supports:

    • background-color
    • color
    • text-decoration and its associated properties (text-underline-position and text-underline-offset), as well as its associated constituent properties:
      • text-decoration-color
      • text-decoration-line: But only the grammar-error, spelling-error, line-through, none, and underline values.
      • text-decoration-skip-ink
      • text-decoration-style
      • text-decoration-thickness
    • text-shadow
    • Custom properties

    And, yes, we can use it with custom properties, like:

    :root {
      --color-blueberry: oklch(0.5458 0.1568 241.39);
    }
    ::search-text {
      background-color: var(--color-blueberry);
    }

    Basic usage

    With the ::search-text pseudo-element, we can style the matching text results from “Find in page”. Plus, if we want to style the currently focused matching text, then we attach the :current pseudo-class after ::search-text.

    /* matches all searched text */
    ::search-text {
      color: green;
      background-color: white;
    }
    /* matches any header level 1 searched text */
    h1::search-text {
      text-shadow: 12px 1px lightgrey;
      background-color: black;
      color: white;
    }
    /* the current searched header level 1 text */
    h1::search-text:current {
      color: red;
      background: white;
    }
    CodePen Embed Fallback

    Inheritance chain

    All descendants always inherit styles applied through the highlight pseudo-elements. This way, individual properties set on highlights will cascade to all elements down the three. Take for example the following HTML:

    <article>
      <h2>Highlight inheritance demo</h2>
      <p>Lorem ipsum dolor sit amet. <strong>Lorem</strong> appears again here. Another lorem appears here.
      </p>
    </article>

    We have an <article> container with two children: <h2> and <p>, the latter having a <strong> descendant of its own. We could style ::search-text in <article> with the following CSS, which would apply to all elements in <article>:

    article::search-text {
      background: gold;
      color: black;
      text-decoration: underline;
    }

    Then, override the color property for only <p> and its descendants:

    p::search-text {
      color: orange;
    }

    And do the same for text-decoration on the <strong> element:

    strong::search-text {
      text-decoration: line-through;
    }

    When you search for “lorem”, the background of the first instance (inside <p> but outside <strong>) will inherit both the background and text-decoration values from <article>, while overriding its color value with its own orange.

    Onto <strong>‘s “lorem” text, it will inherit the properties we set in its parent <p> and grandparent <article. So the color and background values are inherited directly from its parent, and since they haven’t been overridden, they stay. While we override the text-decoration value to line-through.

    CodePen Embed Fallback

    The key takeaway from this example is that properties for highlight elements are also individually inherited and overridden.

    Targeting a text

    In the demo below, we set text-decoration to underline to give any searched text a blue underline. This way, we can customize matching text while also leaving the default background color, which prevents people from getting confused about what’s going on.

    ::search-text {
      text-decoration: underline;
      text-decoration-color: oklch(65% 0.18 240);
      text-decoration-thickness: 0.22em;
      text-underline-offset: 0.15em;
    }
    CodePen Embed Fallback

    Using :current

    Using ::search-text with :current, we can style the currently focused match. For example, below we apply a light orange hue text decoration color with 0.3em thickness to the currently matched searched text:

    ::search-text:current {
      text-decoration-color: oklch(85% 0.22 38);
      text-decoration-thickness: 0.3em;
    }
    CodePen Embed Fallback

    Some accessibility notes

    For WCAG’s contrast standards, you need a contrast ratio of at least 4.5:1 between the text and background. Another piece of advice is not to change the search colors too much. In fact, this feature should be used sparingly since it may cause issues for users with cognitive issues, and as a core part of the browser, it can be generally confusing. My personal advice is to stick to only text-decoration and its associated properties since they are more subtle than the rest.

    There’s also :past and :future

    The :past and :future pseudo-classes are supposed to match the element entirely prior and entirely after a :current element, respectively.

    However, the specification says:

    The :past and :future pseudo-classes are reserved for analogous use in the future. Any unsupported combination of these pseudo-classes with ::search-text must be treated as invalid

    Meaning, you can’t use :past, :future or any other pseudo-class with the ::search-text pseudo-element. If your browser somehow works with them, kindly report the unexpected behavior by opening an issue with them.

    Specification

    The CSS ::search-text pseudo-element is defined in the CSS Pseudo-Elements Module Level 4 specification. This is still being tested and improved upon.

    Browser support

    Very wide support:

    Related tricks!

    pseudo elements
    Article on Jan 28, 2026

    Styling ::search-text and Other Highlight-y Pseudo-Elements

    Daniel Schwarz
    accessibility attributes HTML
    Article on Aug 15, 2025

    Covering hidden=until-found

    Geoff Graham


    ::search-text originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-06-01 13:25
    ↗

    In the previous article, I spoke about the why and how to use a Markdown component in Astro. Here, we’re going to expand on that and help you use Markdown everywhere — regardless of the framework you use. So, … Astro Markdown Component Utility for Any Framework originally...

    In the previous article, I spoke about the why and how to use a Markdown component in Astro.

    Here, we’re going to expand on that and help you use Markdown everywhere — regardless of the framework you use. So, this works for React, Vue, and Svelte.

    The entire process hinges on the Markdown utility I’ve built for Splendid Labz.

    Why This Utility?

    I hit a snag when using most Markdown libraries. I naturally write Markdown content like this:

    <div>
      <div>
        <!-- prettier-ignore -->
        <Markdown>
          This is a paragraph
    
          This is a second paragraph
        </Markdown>
      </div>
    </div>

    But since most markdown libraries don’t account for whitespace indentation, they create an output with <pre> and <code> tags.

    This is because Markdown treats the indentation beyond four spaces as a code block:

    <div>
      <div>
        <pre><code>  This is a paragraph
    
          This is a second paragraph
        </code></pre>
      </div>
    </div>

    So you’re forced to strip all indentation and write it like this instead:

    <div>
      <div>
        <!-- prettier-ignore -->
        <Markdown>
      This is a paragraph
    
      This is a second paragraph
        </Markdown>
      </div>
    </div>

    That’s hard to read and annoying to maintain.

    My Markdown utility handles this whitespace issue and generates the correct HTML regardless of how your code is indented:

    <div>
      <div>
        <p>This is a paragraph</p>
        <p>This is a second paragraph</p>
      </div>
    </div>

    Using This in Your Framework

    It’s easy. You have to pass the Markdown text into the utility. If inline is true, then markdown will return an output without paragraph tags.

    Here’s an example with Astro.

    ---
    import { markdown } from '@splendidlabz/utils'
    const { inline = false, content } = Astro.props
    const slotContent = await Astro.slots.render('default')
    
    // Process content
    const html = markdown(content || slotContent, { inline })
    ---
    
    <Fragment set:html={html} />

    You can then use it like this:

    <Markdown>
       <!-- Your content here -->
    </Markdown>

    Here’s another example for Svelte.

    Svelte cannot read dynamic content from slots, so we can only pass it through a prop.

    <script>
      import { markdown } from '@splendidlabz/utils'
      const { content, inline = false } = $props()
      const html = markdown(content, { inline })
    </script>
    
    <!-- eslint-disable-next-line svelte/no-at-html-tags -->
    {@html html}

    And you can use it like this:

    <Markdown content=`
      ### This is a header
    
      This is a paragraph
    `/>

    It’s rather simple to build the same for React and Vue so I’d leave that up to you.

    Taking it Further

    I’ve been building for the web — long enough to experience the frustration of doing the same things over and over again.

    So I consolidated everything I use into a few simple libraries — like Splendid Utils, and a few others for layouts, Astro and Svelte components.

    I write about all of them on my blog. Come by if you’re interested in better DX as you build your sites and apps!


    Astro Markdown Component Utility for Any Framework originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-05-29 13:25
    ↗

    The old (testing in Safari when you don’t have Safari), the new (::checkmark), the in-between (anchor positioning but with HTML), and more. What’s !important #12: Safari Testing, ::checkmark, HTML Anchor Positioning, and More originally handwritten and published with love on...

    What’s !important #12 talks about the old (testing in Safari when you don’t have Safari), the new (::checkmark), the in-between (anchor positioning but with HTML), and more.

    Buckle up!

    Testing in Safari when you don’t have Safari

    A Safari browser window on macOS showing an About Safari dialogue box with a translucent red and orange noise filter.
    Source: Frontend Masters

    Safari is the second most popular web browser, but is only available to Apple users. Fair enough. I mean, Apple are heavily invested in making Safari a proprietary browser that’s deeply integrated with Apple’s software and hardware. However, this makes testing websites in Safari a bit of a pain. Declan Chidlow explained what our options are in regards to testing in Safari when you don’t have Safari.

    A first look at ::checkmark

    Sunkanmi Fafowora gave us our first look at the ::checkmark pseudo-element, which solves the age-old problem of not (really) being able to style checkmarks. Note that this also targets the checked state indicator of radios and selects, not just checkboxes!

    Different shape styles with border-shape + shape()

    Temani Afif pointed out that we can create more shape styles when combining border-shape with the shape() function (compared to clip-path), and, easily switch between them.

    Three variations of a wavy shape rendered in red, showing an outline version, a solid filled version, and a cutout version inside a solid red square.
    Source: CSS Tip

    A concise guide to sibling-index() and sibling-count()

    Durgesh Pawar did a deep dive on sibling-index() and sibling-count(), showing us all of the cool things that we can do with these almost-Baseline CSS functions.

    CodePen Embed Fallback

    Also, don’t miss Durgesh’s two-part series about View Transition gotchas right here on CSS-Tricks.

    Managing anchor associations with data attributes and advanced attr()

    This one’s actually from me! Disappointed to hear that the anchor attribute has been dropped, which would’ve provided a way of managing anchor associations using HTML, I demonstrated my alternative technique that involves managing anchor associations with data attributes and advanced attr().

    I won’t spoiler the CSS, but here are the different HTML syntaxes that I explored:

    <!-- anchor attribute -->
    <div anchor="anchorA">Boat A</div>
    <div id="anchorA">Anchor A</div>
    
    <!-- Data attributes with custom ident (requires attr()) -->
    <div data-boat="--anchorA">Boat A</div>
    <div data-anchor="--anchorA">Anchor A</div>
    
    <!-- Data attributes (requires attr() and ident()) -->
    <div data-boat="anchorA">Boat A</div>
    <div data-anchor="anchorA">Anchor A</div>

    Take the State of CSS 2026 survey

    The official graphic for the State of CSS 2026 survey, featuring a stylized CSS logo inside a pink and purple diamond emblem against a dark background.

    It’s that time of the year again!

    I love these “state of” surveys (especially the State of CSS 2026 survey, but I’m sure you know that already). This year feels different though, and I’m not the only one that’s noticed.

    From the opening crawl:

    Take a deep breath. Calm down. It’s ok if you don’t know every single new CSS property. The truth is, very few of us do.

    Look, one of this survey’s goals has always been to help keep developers up to date on the latest and greatest CSS improvements. But the downside is that all this progress can sometimes feel overwhelming.

    That’s why this year we made a conscious effort to reduce the number of features covered in the survey, focusing instead on the ones that matter most.

    I totally get it. It’s becoming more and more difficult to keep up with CSS. My “things to check out” list just keeps getting longer! That being said, there’s never been a more exciting time to be a fan of CSS. That feeling when you learn a new feature and then two more get shipped, is overwhelming but in the best way possible.

    But still, time doesn’t grow on trees, so we have to figure out which features to invest in, and that’s what these “state of” surveys are all about. And they’re going hard this year, really zeroing in on the most important ones.

    But, if you have an appetite for all things CSS, I hear there’s a great blog for that!

    New web platform features

    • Firefox 151
      • Container style queries (now Baseline)
      • Document Picture-in-Picture API (desktop only, no Safari support)

    Quality over quantity, I guess!

    Until next time.


    What’s !important #12: Safari Testing, ::checkmark, HTML Anchor Positioning, and More originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • CSS-Tricks css-tricks.com css css-tricks frontend technology web-dev web-development 2026-05-27 12:37
    ↗

    Until we get something like ::nth-letter, there are still some really cool text effects we can make from existing CSS features, like letter-spacing, ::first-word and ::first-line. Revealing Text With CSS letter-spacing originally handwritten and published with love on...

    Some text effects are relatively hard to pull in CSS, the main reason being we are unable to target individual characters (something many of us want in the form of ::nth-letter(), although we have basis for it with ::first-letter that gives us access to a box element’s first glyph.

    But maybe there are a few things we can use today with what we already have.

    For example, the CSS letter-spacing property adjusts the space between all characters in a block of text. Positive values add space to the right side of each glyph (in a left-to-right writing mode), and negative values shrink the width of the glyph box, causing letters to overlap and even move the other way.

    CodePen Embed Fallback

    The letter-spacing accepts length units, and percentage (relative to font size). It is animateable, and as we saw before, the negative values can shrink it down or reverse it. Which is something we can make use of.

    Overlapping and separating letters

    It’s quite easy to completely overlap the characters as a starting point and setting it’s color to transparent to visually hide it.

    label {
      letter-spacing: -1ch;
      color: transparent;
      /* etc. */
    }

    From there, we can reveal the text by animating that letter-spacing value to a positive value and updating the color to a visible value, like when a checkbox is :checked:

    li:nth-of-type(2) label {
      text-align: center;
    }
    li:nth-of-type(3) label {
      text-align: right;
    }
    input:checked + label {
      letter-spacing: 0ch;
      color: black;
      transition: letter-spacing 0.6s, color 0.4s;
    }
    CodePen Embed Fallback

    Note: The CSS ch unit is a relative length representing the width of the zero (0) glyph.

    The labels go from negative letter-spacing to normal spacing and the color updates to black. Both these changes happen over a transition.

    The second and third labels are given center and right text alignments and thus when negative letter spacing is applied they bundle up at the given alignment position, center and right, respectively. When letter``-``spacing goes from negative to zero (or any positive value) the letters separate from that same alignment position.

    Thus, we get a text reveal effect! Let’s look at some more.

    Showing and hiding text

    Check this out. We can toggle a checkbox label as a fun interactive UI touch:

    CodePen Embed Fallback
    <!-- Simplified for brevity; additional accessibility considerations -->
    <input type="checkbox" id="cb">
    <label for="cb">
      <span>Join the global club</span>
      <span>You've begun your journey!</span>
    </label>
    label {
      overflow: clip;
      /* etc. */
    }
    
    span {
      /* The first label */
      &:nth-of-type(1) {
        /* Default spacing: letters are fully visible */
        letter-spacing: 0ch;
        /* When the checkbox is checked, target this text */
        :checked + * & {
          /* collapse letters on top of each other, hiding them */
          letter-spacing: -2ch;
          text-indent: -1.5ch;
          /* Use a "bouncy" cubic-bezier for spacing */
          transition: 0.4s letter-spacing cubic-bezier(.8, -.5, .2, 1.4), 
                      0.1s text-indent;
        }
      }
      
      /* The second label */
      &:nth-of-type(2) { 
        /* Initially collapsed (letters overlap) */
        letter-spacing: -1ch;
        color: transparent;
        /* When the checkbox is checked, target this text */
        :checked + * & {
          /* Returns to normal spacing */
          letter-spacing: 0ch;
          color: black;
          /* Slightly delay the appearance so it starts after the first text begins to hide */
          transition:
            0.4s letter-spacing cubic-bezier(.8, -.5, .2, 1.4) 0.3s, 
            0.8s color 0.4s;
        }
      }
    }

    When the box is checked, a negative letter-spacing value (-2ch) and text-indent value (-1.5ch) is used on the first <span> to slide it out of the container box. We use overflow: clip to completely hide the text.

    Concurrently, the text in the second <span> text goes from a letter-spacing value of -1ch to 0ch, which reveals it. To hide this overlapped text at -1ch, a transparent color was given that’s turned to black when the checkbox is checked.

    Using with other glyph box styling

    Here’s another fun one. We can start with an acronym that reveal the full text on hover. Again, we have existing features to help us pull this off, including ::first-letter and ::first-line.

    We’ll start with this markup:

    <!-- Simplified for brevity -->
    <p id="acronym">
      <span class="words">United</span>
      <span class="words">Nations</span>
      <span class="words">International</span>
      <span class="words">Children's</span>
      <span class="words">Emergency</span>
      <span class="words">Fund</span>
    </p>
    .words {
      letter-spacing: -1ch;
      color: transparent;
      /* etc. */
    
      &::first-letter {
        color: black;
      }
    
      figure:hover + #acronym & {
        letter-spacing: 0ch;
        color: black;
        transition: letter-spacing 0.4s cubic-bezier(.8, -.5, .2, 1.4) /* etc. */;
      }
    }

    Each word in the UNICEF acronym initially has letter-spacing: -1ch to shrink the text, and color: transparent to keep the shrunk text hidden, except the ::first-letter that has color: black so it remains visible even though the rest of the text is stacked beneath it.

    Now, we can target the image on :hover and select the entire text so that the letter-spacing value for each word decreases to 0ch and color: black is applied, showing what’s remaining of the words:

    CodePen Embed Fallback

    What else can we do?

    I don’t know! But that’s where you come in. Obviously, a hypothetical ::nth-letter selector would be amazing for all kinds of text effects. But it’s neat that we can create some semblance of it today with existing features, like letter-spacing, ::first-letter, and ::first-line.

    What can you cook up knowing we have these constraints?


    Revealing Text With CSS letter-spacing originally handwritten and published with love on CSS-Tricks. You should really get the newsletter as well.

  • End of feed
Maibook — your private personalized AI community
  • rcanand.com
  • mlaillc.com
  • @rcanand (X)
  • LinkedIn
  • Feedback
  • Credits