Web Standards

Come to the light-dark() Side

Css Tricks - Fri, 10/25/2024 - 4:08am

You’d be forgiven for thinking coding up both a dark and a light mode at once is a lot of work. You have to remember @media queries based on prefers-color-scheme as well as extra complications that arise when letting visitors choose whether they want light or dark mode separately from the OS setting. And let’s not forget the color palette itself! Switching from a “light” mode to a “dark” mode may involve new variations to get the right amount of contrast for an accessible experience.

It is indeed a lot of work. But I’m here to tell you it’s now a lot simpler with modern CSS!

Default HTML color scheme(s)

We all know the “naked” HTML theme even if we rarely see it as we’ve already applied a CSS reset or our favorite boilerplate CSS before we even open localhost. But here’s a news flash: HTML doesn’t only have the standard black-on-white theme, there is also a native white-on-black version.

We have two color schemes available to use right out of the box!

If you want to create a dark mode interface, this is a great base to work with and saves you from having to account for annoying details, like dark inputs, buttons, and other interactive elements.

Live Demo on CodePen Switching color schemes automatically based on OS preference

Without any @media queries — or any other CSS at all — if all we did was declare color-scheme: light dark on the root element, the page will apply either the light or dark color scheme automatically by looking at the visitor’s operating system (OS) preferences. Most OSes have a built-in accessibility setting for your preferred color scheme — “light”, “dark”, or even “auto” — and browsers respect that setting.

html { color-scheme: light dark; }

We can even accomplish this without CSS directly in the HTML document in a <meta> tag:

<meta name="color-scheme" content="light dark">

Whether you go with CSS or the HTML route, it doesn’t matter — they both work the same way: telling the browser to make both light and dark schemes available and apply the one that matches the visitor’s preferences. We don’t even need to litter our styles with prefers-color-scheme instances simply to swap colors because the logic is built right in!

You can apply light or dark values to the color-scheme property. At the same time, I’d say that setting color-scheme: light is redundant, as this is the default color scheme with or without declaring it.

You can, of course, control the <meta> tag or the CSS property with JavaScript.

There’s also the possibility of applying the color-scheme property on specific elements instead of the entire page in one fell swoop. Then again, that means you are required to explicitly declare an element’s color and background-color properties; otherwise the element is transparent and inherits its text color from its parent element.

What values should you give it? Try:

Default text and background color variables

The “black” colors of these native themes aren’t always completely black but are often off-black, making the contrast a little easier on the eyes. It’s worth noting, too, that there’s variation in the blackness of “black” between browsers.

What is very useful is that this default not-pure-black and maybe-not-pure-white background-color and text color are available as <system-color> variables. They also flip their color values automatically with color-scheme!

They are: Canvas and CanvasText.

These two variables can be used anywhere in your CSS to call up the current default background color (Canvas) or text color (CanvasText) based on the current color scheme. If you’re familiar with the currentColor value in CSS, it seems to function similarly. CanvasText, meanwhile, remains the default text color in that it can’t be changed the way currentColor changes when you assign something to color.

In the following examples, the only change is the color-scheme property:

Not bad! There are many, many more of these system variables. They are case-insensitive, often written in camelCase or PascalCase for readability. MDN lists 19 <system-color> variables and I’m dropping them in below for reference.

Open to view 19 system color names and descriptions
  • AccentColor: The background color for accented user interface controls
  • AccentColorText: The text color for accented user interface controls
  • ActiveText: The text color of active links
  • ButtonBorder: The base border color for controls
  • ButtonFace: The background color for controls
  • ButtonText: The text color for controls
  • Canvas: The background color of an application’s content or documents
  • CanvasText: The text color used in an application’s content or documents
  • Field: The background color for input fields
  • FieldText: The text color inside form input fields
  • GrayText: The text color for disabled items (e.g., a disabled control)
  • Highlight: The background color for selected items
  • HighlightText: The text color for selected items
  • LinkText: The text color used for non-active, non-visited links
  • Mark: The background color for text marked up in a <mark> element
  • MarkText: The text color for text marked up in a <mark> element
  • SelectedItem: The background color for selected items (e.g., a selected checkbox)
  • SelectedItemText: The text color for selected items
  • VisitedText: The text visited links

Cool, right? There are many of them! There are, unfortunately, also discrepancies as far as how these color keywords are used and rendered between different OSes and browsers. Even though “evergreen” browsers arguably support all of them, they don’t all actually match what they’re supposed to, and fail to flip with the CSS color-scheme property as they should.

Egor Kloos (also known as dutchcelt) is keeping an eye on the current status of system colors, including which ones exist and the browsers that support them, something he does as part of a classless CSS framework cleverly called system.css.

CodePen Embed Fallback Declaring colors for both modes together

OK good, so now you have a page that auto-magically flips dark and light colors according to system preferences. Whether you choose to use these system colors or not is up to you. I just like to point out that “dark” doesn’t always have to mean pure “black” just as “light” doesn’t have to mean pure “white.” There are lots more colors to pair together!

But what’s the best or simplest way to declare colors so they work in both light and dark mode?

In my subjective reverse-best order:

Third place: Declare color opacity

You could keep all the same background colors in dark and light modes, but declare them with an opacity (i.e. rgb(128 0 0 / 0.5) or #80000080). Then they’ll have the Canvas color shine through.

It’s unusable in this way for text colors, and you may end up with somewhat muted colors. But it is a nice easy way to get some theming done fast. I did this for the code blocks on this old light and dark mode demo.

Second place: Use color-mix()

Like this:

color-mix(in oklab, Canvas 75%, RebeccaPurple);

Similar (but also different) to using opacity to mute a color is mixing colors in CSS. We can even mix the system color variables! For example, one of the colors can be either Canvas or CanvasText so that the background color always mixes with Canvas and the text color always mixes with CanvasText.

We now have the CSS color-mix() function to help us with this. The first argument in the function defines the color space where the color mixing happens. For example, we can tell the function that we are working in the OKLAB color space, which is a rectangular color space like sRGB making it ideal to mix with sRGB color values for predictable results. You can certainly mix colors from different color spaces — the OKLAB/sRGB combination happens to work for me in this instance.

The second and third arguments are the colors you want to mix, and in what proportion. Proportions are optional but expressed in percentages. Without declaring a proportion, the mix is an even 50%-50% split. If you add percentages for both colors and they don’t match up to 100%, it does a little math for you to prevent breakages.

The color-mix() approach is useful if you’re happy to keep the same hues and color saturations regardless of whether the mode is light or dark.

In this example, as you change the value of the hue slider, you’ll see color changes in the themed boxes, following the theme color but mixed with Canvas and CanvasText:

CodePen Embed Fallback

You may have noticed that I used OKLCH and HSL color spaces in that last example. You may also have noticed that the HSL-based theme color and the themed paragraph were a lot more “flashy” as you moved the hue slider.

I’ve declared colors using a polar color space, like HSL, for years, loving that you can easily take a hue and go up or down the saturation and lightness scales based on need. But, I concede that it’s problematic if you’re working with multiple hues while trying to achieve consistent perceived lightness and saturation across them all. It can be difficult to provide ample contrast across a spectrum of colors with HSL.

The OKLCH color space is also polar just like HSL, with the same benefits. You can pick your hue and use the chroma value (which is a bit like saturation in HSL) and the lightness scales accurately in the same way. Both OKLCH and OKLAB are designed to better match what our eyes perceive in terms of brightness and color compared to transitioning between colors in the sRGB space.

While these color spaces may not explicitly answer the age-old question, Is my blue the same as your blue? the colors are much more consistent and require less finicking when you decide to base your whole website’s palette on a different theme color. With these color spaces, the contrasts between the computed colors remain much the same.

First place (winner!): Use light-dark()

Like this:

light-dark(lavender, saddlebrown);

With the previous color-mix() example, if you choose a pale lavender in light mode, its dark mode counterpart is very dark lavender.

The light-dark() function, conversely, provides complete control. You might want that element to be pale lavender in light mode and a deep burnt sienna brown in dark mode. Why not? You can still use color-mix() within light-dark() if you like — declare the colors however you like, and gain much more fine-grained control over your colors.

Feel free to experiment in the following editable demo:

CodePen Embed Fallback

Using color-scheme: light dark; — or the corresponding meta tag in HTML on your page —is a prerequisite for the light-dark() function because it allows the function to respect a person’s system preference, or whichever single light or dark value you have set on color-scheme.

Another consideration is that light-dark() is newly available across browsers, with just over 80% coverage across all users at the time I’m writing this. So, you might consider including a fallback in your CSS for browsers that lack support for the function.

What makes using color-scheme and light-dark() better than using @media queries?

@media queries have been excellent tools, but using them to query prefers-color-scheme only ever follows the preference set within the person’s operating system. This is fine until you (rightfully) want to offer the visitor more choices, decoupled from whether they prefer the UI on their device to be dark or light.

We’re already capable of doing that, of course. We’ve become used to a lot of jiggery-pokery with extra CSS classes, using duplicated styles, or employing custom properties to make it happen.

The joy of using color-scheme is threefold:

  • It gives you the basic monochrome dark mode for free!
  • It can natively do the mode switching based on OS mode preference.
  • You can use JavaScript to toggle between light and dark mode, and the colors declared in the light-dark() functions will follow it.
Light, dark, and auto mode controls

Essentially, all we are doing is setting one of three options for whether the color-scheme is light, dark, or updates auto-matically.

I advise offering all three as discrete options, as it removes some complications for you! Any new visitor to the site will likely be in auto mode because accepting the visitor’s OS setting is the least jarring default state. You then give that person the choice to stay with that or swap it out for a different color scheme. This way, there’s no need to sniff out what mode someone prefers to, for example, display the correct icon on a toggle and make it perform the correct action. There is also no need to keep an event listener on prefers-color-scheme in case of changes — your color-scheme: light dark declaration in CSS handles that for you.

Adjusting color-scheme in pure CSS

Yes, this is totally possible! But the approach comes with a few caveats:

  • You can’t use <button> — only radio inputs, or <options> in a <select> element.
  • It only works on a per page basis, not per website, which means changes are lost on reload or refresh.
  • The browser needs to support the :has() pseudo-selector. Most modern browsers do, but some folks using older devices might miss out on the experience.
Using the :has() pseudo-selector

This approach is almost alarmingly simple and is fantastic for a simple one-pager! Most of the heavy lifting is done with this:

/* default, or 'auto' */ html { color-scheme: light dark; } html:has([value="light"]:checked { color-scheme: light; } html:has([value="dark"]:checked { color-scheme: dark; }

The second and third rulesets above look for an attribute called value on any element that has “light” or “dark” assigned to it, then change the color-scheme to match only if that element is :checked.

This approach is not very efficient if you have a huge page full of elements. In those cases, it’s better to be more specific. In the following two examples, the CSS selectors check for value only within an element containing id="mode-switcher".

html:has(#mode-switcher [value="light"]:checked) { color-scheme: light } /* Did you know you don't need the ";" for a one-liner? Now you do! */

Using a <select> element:

CodePen Embed Fallback

Using <input type="radio">:

CodePen Embed Fallback

We could theoretically use checkboxes for this, but since checkboxes are not supposed to be used for mutually exclusive options, I won’t provide an example here. What happens in the case of more than one option being checked? The last matching CSS declaration wins (which is dark in the examples above).

Adjusting color-scheme in HTML with JavaScript

I subscribe to Jeremy Keith’s maxim when it comes to reaching for JavaScript:

JavaScript should only do what only JavaScript can do.

This is exactly that kind of situation.

If you want to allow visitors to change the color scheme using buttons, or you would like the option to be saved the next time the visitor comes to the site, then we do need at least some JavaScript. Rather than using the :has() pseudo-selector in CSS, we have a few alternative approaches for changing the color-scheme when we add JavaScript to the mix.

Using <meta> tags

If you have set your color-scheme within a meta tag in the <head> of your HTML:

<meta name="color-scheme" content="light dark">

…you might start by making a useful constant like so:

const colorScheme = document.querySelector('meta[name="color-scheme"]');

And then you can manipulate that, assigning it light or dark as you see fit:

colorScheme.setAttribute("content", "light"); // to light mode colorScheme.setAttribute("content", "dark"); // to dark mode colorScheme.setAttribute("content", "light dark"); // to auto mode

This is a very similar approach to using <meta> tags but is different if you are setting the color-scheme property in CSS:

html { color-scheme: light dark; }

Instead of setting a colorScheme constant as we just did in the last example with the <meta> tag, you might select the <html> element instead:

const html = document.querySelector('html');

Now your manipulations look like this:

html.style.setProperty("color-scheme", "light"); // to light mode html.style.setProperty("color-scheme", "dark"); // to dark mode html.style.setProperty("color-scheme", "light dark"); // to auto mode

I like to turn those manipulations into functions so that I can reuse them:

function switchAuto() { html.style.setProperty("color-scheme", "light dark"); } function switchLight() { html.style.setProperty("color-scheme", "light"); } function switchDark() { html.style.setProperty("color-scheme", "dark"); }

Alternatively, you might like to stay as DRY as possible and do something like this:

function switchMode(mode) { html.style.setProperty("color-scheme", mode === "auto" ? "light dark" : mode); }

The following demo shows how this JavaScript-based approach can be used with buttons, radio buttons, and a <select> element. Please note that not all of the controls are hooked up to update the UI — the demo would end up too complicated since there’s no world where all three types of controls would be used in the same UI!

CodePen Embed Fallback

I opted to use onchange and onclick in the HTML elements mainly because I find them readable and neat. There’s nothing wrong with instead attaching a change event listener to your controls, especially if you need to trigger other actions when the options change. Using onclick on a button doesn’t only work for clicks, the button is still keyboard-focusable and can be triggered with Spacebar and Enter too, as usual.

Remembering the selection for repeat visits

The biggest caveat to everything we’ve covered so far is that this only works once. In other words, once the visitor has left the site, we’re doing nothing to remember their color scheme preference. It would be a better user experience to store that preference and respect it anytime the visitor returns.

The Web Storage API is our go-to for this. And there are two available ways for us to store someone’s color scheme preference for future visits.

localStorage

Local storage saves values directly on the visitor’s device. This makes it a nice way to keep things off your server, as the stored data never expires, allowing us to call it anytime. That said, we’re prone to losing that data whenever the visitor clears cookies and cache and they’ll have to make a new selection that is freshly stored in localStorage.

You pick a key name and give it a value with .setItem():

localStorage.setItem("mode", "dark");

The key and value are saved by the browser, and can be called up again for future visits:

const mode = localStorage.getItem("mode");

You can then use the value stored in this key to apply the person’s preferred color scheme.

sessionStorage

Session storage is thrown away as soon as a visitor browses away to another site or closes the current window/tab. However, the data we capture in sessionStorage persists while the visitor navigates between pages or views on the same domain.

It looks a lot like localStorage:

sessionStorage.setItem("mode", "dark"); const mode = sessionStorage.getItem("mode"); Which storage method should I use?

Personally, I started with sessionStorage because I wanted my site to be as simple as possible, and to avoid anything that would trigger the need for a GDPR-compliant cookie banner if we were holding onto the person’s preference after their session ends. If most of your traffic comes from new visitors, then I suggest using sessionStorage to prevent having to do extra work on the GDPR side of things.

That said, if your traffic is mostly made up of people who return to the site again and again, then localStorage is likely a better approach. The convenience benefits your visitors, making it worth the GDPR work.

The following example shows the localStorage approach. Open it up in a new window or tab, pick a theme other than what’s set in your operating system’s preferences, close the window or tab, then re-open the demo in a new window or tab. Does the demo respect the color scheme you selected? It should!

CodePen Embed Fallback

Choose the “Auto” option to go back to normal.

If you want to look more closely at what is going on, you can open up the developer tools in your browser (F12 for Windows, CTRL+ click and select “Inspect” for macOS). From there, go into the “Application” tab and locate https://cdpn.io in the list of items stored in localStorage. You should see the saved key (mode) and the value (dark or light). Then start clicking on the color scheme options again and watch the mode update in real-time.

Accessibility

Congratulations! If you have got this far, you are considering or already providing versions of your website that are more comfortable for different people to use.

For example:

  • People with strong floaters in their eyes may prefer to use dark mode.
  • People with astigmatism may be able to focus more easily in light mode.

So, providing both versions leaves fewer people straining their eyes to access the content.

Contrast levels

I want to include a small addendum to this provision of a light and dark mode. An easy temptation is to go full monochrome black-on-white or white-on-black. It’s striking and punchy! I get it. But that’s just it — striking and punchy can also trigger migraines for some people who do a lot better with lower contrasts.

Providing high contrast is great for the people who need it. Some visual impairments do make it impossible to focus and get a sharp image, and a high contrast level can help people to better make out the word shapes through a blur. Minimum contrast levels are important and should be exceeded.

Thankfully, alongside other media queries, we can also query prefers-contrast which accepts values for no-preference, more, less, or custom.

In the following example (which uses :has() and color-mix()), a <select> element is displayed to offer contrast settings. When “Low” is selected, a filter of contrast(75%) is placed across the page. When “High” is selected, CanvasText and Canvas are used unmixed for text color and background color:

CodePen Embed Fallback

Adding a quick high and low contrast theme gives your visitors even more choice for their reading comfort. Look at that — now you have three contrast levels in both dark and light modes — six color schemes to choose from!

ARIA-pressed

ARIA stands for Accessible Rich Internet Applications and is designed for adding a bit of extra info where needed to screen readers and other assistive tech.

The words “where needed” do heavy lifting here. It has been said that, like apostrophes, no ARIA is better than bad ARIA. So, best practice is to avoid putting it everywhere. For the most part (with only a few exceptions) native HTML elements are good to go out of the box, especially if you put useful text in your buttons!

The little bit of ARIA I use in this demo is for adding the aria-pressed attribute to the buttons, as unlike a radio group or select element, it’s otherwise unclear to anyone which button is the “active” one, and ARIA helps nicely with this use case. Now a screen reader will announce both its accessible name and whether it is in a pressed or unpressed state along with a button.

Following is an example code snippet with all the ARIA code bolded — yes, suddenly there’s lots more! You may find more elegant (or DRY-er) ways to do this, but showing it this way first makes it more clear to demonstrate what’s happening.

Our buttons have ids, which we have used to target them with some more handy consts at the top. Each time we switch mode, we make the button’s aria-pressed value for the selected mode true, and the other two false:

const html = document.querySelector("html"); const mode = localStorage.getItem("mode"); const lightSwitch = document.querySelector('#lightSwitch'); const darkSwitch = document.querySelector('#darkSwitch'); const autoSwitch = document.querySelector('#autoSwitch'); if (mode === "light") switchLight(); if (mode === "dark") switchDark(); function switchAuto() { html.style.setProperty("color-scheme", "light dark"); localStorage.removeItem("mode"); lightSwitch.setAttribute("aria-pressed","false"); darkSwitch.setAttribute("aria-pressed","false"); autoSwitch.setAttribute("aria-pressed","true"); } function switchLight() { html.style.setProperty("color-scheme", "light"); localStorage.setItem("mode", "light"); lightSwitch.setAttribute("aria-pressed","true"); darkSwitch.setAttribute("aria-pressed","false"); autoSwitch.setAttribute("aria-pressed","false"); } function switchDark() { html.style.setProperty("color-scheme", "dark"); localStorage.setItem("mode", "dark"); lightSwitch.setAttribute("aria-pressed","false"); darkSwitch.setAttribute("aria-pressed","true"); autoSwitch.setAttribute("aria-pressed","false"); }

On load, the buttons have a default setting, which is when the “Auto” mode button is active. Should there be any other mode in the localStorage, we pick it up immediately and run either switchLight() or switchDark(), both of which contain the aria-pressed changes relevant to that mode.

<button id="autoSwitch" aria-pressed="true" type="button" onclick="switchAuto()">Auto</button> <button id="lightSwitch" aria-pressed="false" type="button" onclick="switchLight()">Light</button> <button id="darkSwitch" aria-pressed="false" type="button" onclick="switchDark()">Dark</button>

The last benefit of aria-pressed is that we can also target it for styling purposes:

button[aria-pressed="true"] { background-color: transparent; border-width: 2px; }

Finally, we have a nice little button switcher, with its state clearly shown and announced, that remembers your choice when you come back to it. Done!

CodePen Embed Fallback Outroduction

Or whatever the opposite of an introduction is…

…don’t let yourself get dragged into the old dark vs light mode argument. Both are good. Both are great! And both modes are now easy to create at once. At the start of your next project, work or hobby, do not give in to fear and pick a side — give both a try, and give in to choice.

Come to the light-dark() Side originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Left Half and Right Half Layout – Many Different Ways

Css Tricks - Fri, 10/25/2024 - 1:51am

A whole bunch of years ago, we posted on this idea here on CSS-Tricks. We figured it was time to update that and do the subject justice.

Imagine a scenario where you need to split a layout in half. Content on the left and content on the right. Basically two equal height columns are needed inside of a container. Each side takes up exactly half of the container, creating a distinct break between one. Like many things in CSS, there are a number of ways to go about this and we’re going to go over many of them right now!

Update (Oct. 25, 2024): Added an example that uses CSS Anchor Positioning.

Using Background Gradient

One simple way we can create the appearance of a changing background is to use gradients. Half of the background is set to one color and the other half another color. Rather than fade from one color to another, a zero-space color stop is set in the middle.

.container { background: linear-gradient( to right, #ff9e2c 0%, #ff9e2c 50%, #b6701e 50%, #b6701e 100% ); }

This works with a single container element. However, that also means that it will take working with floats or possibly some other layout method if content needs to fill both sides of the container.

CodePen Embed Fallback Using Absolute Positioning

Another route might be to set up two containers inside of a parent container, position them absolutely, split them up in halves using percentages, then apply the backgrounds. The benefit here is that now we have two separate containers that can hold their own content.

CodePen Embed Fallback

Absolute positioning is sometimes a perfect solution, and sometimes untenable. The parent container here will need to have a set height, and setting heights is often bad news for content (content changes!). Not to mention absolute positioned elements are out of the document flow. So it would be hard to get this to work while, say, pushing down other content below it.

Using (fake) Tables

Yeah, yeah, tables are so old school (not to mention fraught with accessibility issues and layout inflexibility). Well, using the display: table-cell; property can actually be a handy way to create this layout without writing table markup in HTML. In short, we turn our semantic parent container into a table, then the child containers into cells inside the table — all in CSS!

CodePen Embed Fallback

You could even change the display properties at breakpoints pretty easily here, making the sides stack on smaller screens. display: table; (and friends) is supported as far back as IE 8 and even old Android, so it’s pretty safe!

Using Floats

We can use our good friend the float to arrange the containers beside each other. The benefit here is that it avoids absolute positioning (which as we noted, can be messy).

CodePen Embed Fallback

In this example, we’re explicitly setting heights to get them to be even. But you don’t really get that ability with floats by default. You could use the background gradient trick we already covered so they just look even. Or look at fancy negative margin tricks and the like.

Also, remember you may need to clear the floats on the parent element to keep the document flow happy.

Using Inline-Block

If clearing elements after floats seems like a burden, then using display: inline-block is another option. The trick here is to make sure that the elements for the individual sides have no breaks or whitespace in between them in the HTML. Otherwise, that space will be rendered as a literal space and the second half will break and fall.

CodePen Embed Fallback

Again there is nothing about inline-block that helps us equalize the heights of the sides, so you’ll have to be explicit about that.

There are also other potential ways to deal with that spacing problem described above.

Using Flexbox

Flexbox is a pretty fantastic way to do this, just note that it’s limited to IE 10 and up and you may need to get fancy with the prefixes and values to get the best support.

Using this method, we turn our parent container into a flexible box with the child containers taking up an equal share of the space. No need to set widths or heights! Flexbox just knows what to do, because the defaults are set up perfectly for this. For instance, flex-direction: row; and align-items: stretch; is what we’re after, but those are the defaults so we don’t have to set them. To make sure they are even though, setting flex: 1; on the sides is a good plan. That forces them to take up equal shares of the space.

CodePen Embed Fallback

In this demo we’re making the side flex containers as well, just for fun, to handle the vertical and horizontal centering.

Using Grid Layout

For those living on the bleeding edge, the CSS Grid Layout technique is like the Flexbox and Table methods merged into one. In other words, a container is defined, then split into columns and cells which can be filled flexibly with child elements.

CodePen Embed Fallback CSS Anchor Positioning

This started rolling out in 2024 and we’re still waiting for full browser support. But we can use CSS Anchor Positioning to “attach” one element to another — even if those two elements are completely unrelated in the markup.

The idea is that we have one element that’s registered as an “anchor” and another element that’s the “target” of that anchor. It’s like the target element is pinned to the anchor. And we get to control where we pin it!

.anchor { anchor-name: --anchor; } .target { anchor-position: --anchor; position: absolute; /* required */ }

This sets up an .anchor and establishes a relationship with a .target element. From here, we can tell the target which side of the anchor it should pin to.

.anchor { anchor-name: --anchor; } .target { anchor-position: --anchor; position: absolute; /* required */ left: anchor(right); } CodePen Embed Fallback

Isn’t it cool how many ways there are to do things in CSS?

Left Half and Right Half Layout – Many Different Ways originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

You can use text-wrap: balance; on icons

Css Tricks - Thu, 10/24/2024 - 4:05am

Terence Eden on using text-wrap: balance for more than headings:

But the name is, I think, slightly misleading. It doesn’t only work on text. It will work on any content. For example – I have a row of icons at the bottom of this page. If the viewport is too narrow, a single icon might drop to the next line. That can look a bit weird.

Heck yeah. I may have reached for some sort of auto-fitting grid approach, but hey, may as well go with a one-liner if you can! And while we’re on the topic, I just wanna mention that, yes, text-wrap: balance will work on any content. — just know that the spec is a little opinionated on this and make sure that the content is fewer than five lines.

There’s likely more nuance to come if the note for Issue 6 in the spec is any indication about possibly allowing for a line length minimum:

Suggestion for value space is match-indent | <length> | <percentage> (with Xch given as an example to make that use case clear). Alternately <integer> could actually count the characters.

You can use text-wrap: balance; on icons originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Clarifying the Relationship Between Popovers and Dialogs

Css Tricks - Wed, 10/23/2024 - 3:20am

The difference between Popovers (i.e., the popover attribute) and Dialogs (i.e., both the <dialog> element and the dialog accessible role) is incredibly confusing — so much that many articles (like this, this, and this) have tried to shed some light on the issue.

If you’re still feeling confused, I hope this one clears up that confusion once and for all.

Distinguishing Popovers From Dialogs

Let’s pull back on the technical implementations and consider the greater picture that makes more sense and puts everything into perspective.

The reason for this categorization comes from a couple of noteworthy points.

First, we know that a popover is content that “pops” up when a user clicks a button (or hovers over it, or focuses on it). In the ARIA world, there is a useful attribute called aria-haspopup that categorizes such popups into five different roles:

  • menu
  • listbox
  • tree
  • grid
  • dialog

Strictly speaking, there’s a sixth value, true, that evaluates to menu. I didn’t include it above since it’s effectively just menu.

By virtue of dialog being on this list, we already know that dialog is a type of popover. But there’s more evidence behind this too.

The Three Types of Dialogues

Since we’re already talking about the dialog role, let’s further expand that into its subcategories:

Dialogs can be categorized into three main kinds:

  • Modal: A dialog with an overlay and focus trapping
  • Non-Modal: A dialog with neither an overlay nor focus trapping
  • Alert Dialog: A dialog that alerts screen readers when shown. It can be either modal or non-modal.

This brings us to another reason why a dialog is considered a popover.

Some people may say that popovers are strictly non-modal, but this seems to be a major misunderstanding — because popovers have a ::backdrop pseudo-element on the top layer. The presence of ::backdrop indicates that popovers are modal. Quoting the CSS-Tricks almanac:

The ::backdrop CSS pseudo-element creates a backdrop that covers the entire viewport and is rendered immediately below a <dialog>, an element with the popup attribute, or any element that enters fullscreen mode using the Fullscreen API.

That said, I don’t recommend using the Popover API for modality because it doesn’t have a showModal() method (that <dialog> has) that creates inertness, focus trapping, and other necessary features to make it a real modal. If you only use the Popover API, you’ll need to build those features from scratch.

So, the fact that popovers can be modal means that a dialog is simply one kind of popover.

A Popover Needs an Accessible Role

Popovers need a role to be accessible. Hidde has a great article on selecting the right role, but I’m going to provide some points in this article as well.

To start, you can use one of the aria-haspopup roles mentioned above:

  • menu
  • listbox
  • tree
  • grid
  • dialog

You could also use one of the more complex roles like:

  • treegrid
  • alertdialog

There are two additional roles that are slightly more contentious but may do just fine.

  • tooltip
  • status

To understand why tooltip and status could be valid popover roles, we need to take a detour into the world of tooltips.

A Note on Tooltips

From a visual perspective, a tooltip is a popover because it contains a tiny window that pops up when the tooltip is displayed.

I included tooltip in the mental model because it is reasonable to implement tooltip with the Popover API.

<div popver role="tooltip">...</div>

The tooltip role doesn’t do much in screen readers today so you need to use aria-describedby to create accessible tooltips. But it is still important because it may extend accessibility support for some software.

But, from an accessibility standpoint, tooltips are not popovers. In the accessibility world, tooltips must not contain interactive content. If they contain interactive content, you’re not looking at a tooltip, but a dialog.

You’re thinking of dialogs. Use a dialog.

Heydon Pickering, “Your Tooltips are Bogus”

This is also why aria-haspopup doesn’t include tooltip —aria-haspopup is supposed to signify interactive content but a tooltip must not contain interactive content.

With that, let’s move on to status which is an interesting role that requires some explanation.

Why status?

Tooltips have a pretty complex history in the world of accessible interfaces so there’s a lot of discussion and contention over it.

To keep things short (again), there’s an accessibility issue with tooltips since tooltips should only show on hover. This means screen readers and mobile phone users won’t be able to see those tooltips (since they can’t hover on the interface).

Steve Faulkner created an alternative — toggletips — to fill the gap. In doing so, he explained that toggletip content must be announced by screen readers through live regions.

When initially displayed content is announced by (most) screen readers that support aria-live

Heydon Pickering later added that status can be used in his article on toggletips.

We can supply an empty live region, and populate it with the toggletip “bubble” when it is invoked. This will both make the bubble appear visually and cause the live region to announce the tooltip’s information.

<!-- Code example by Heydon --> <span class="tooltip-container"> <button type="button" aria-label="more info" data-toggletip-content="This clarifies whatever needs clarifying">i</button> <span role="status"> <span class="toggletip-bubble">This clarifies whatever needs clarifying</span> </span> </span>

This is why status can be a potential role for a popover, but you must use discretion when creating it.

That said, I’ve chosen not to include the status role in the Popover mental model because status is a live region role and hence different from the rest.

In Summary

Here’s a quick summary of the mental model:

  • Popover is an umbrella term for any kind of on-demand popup.
  • Dialog is one type of popover — a kind that creates a new window (or card) to contain some content.

When you internalize this, it’s not hard to see why the Popover API can be used with the dialog element.

<!-- Uses the popover API. Role needs to be determined manually --> <div popover>...</div> <!-- Dialog with the popover API. Role is dialog --> <dialog popover>...</dialog> <!-- Dialog that doesn't use the popover API. Role is dialog --> <dialog>...</dialog>

When choosing a role for your popover, you can use one of these roles safely.

  • menu
  • listbox
  • tree
  • grid
  • treegrid
  • dialog
  • alertdialog

The added benefit is most of these roles work together with aria-haspopup which gained decent support in screen readers last year.

Of course, there are a couple more you can use like status and tooltip, but you won’t be able to use them together with aria-haspopup.

Further Reading

Clarifying the Relationship Between Popovers and Dialogs originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Clamp it! VS Code extension

Css Tricks - Wed, 10/23/2024 - 3:15am

There’s a lot of math behind fluid typography. CSS does make the math a lot easier these days, but even if you’re comfortable with that, writing the full declaration can be verbose and tough to remember. I know I often have to look it back up, despite having written it maybe a hundred times.

Silvestar made a little VS Code helper to abstract all that. Type in the target values you’re aiming for and the helper expands it on the spot.

He says ChatGPT did the initial lifting before he refined it. I can get behind this sort of AI-flavored usage. Start with an idea, find a starting point, look deeper at it, and shape it into something incredibly useful for a small, single purpose.

Clamp it! VS Code extension originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Unleash the Power of Scroll-Driven Animations

Css Tricks - Mon, 10/21/2024 - 3:50am

I’m utterly behind in learning about scroll-driven animations apart from the “reading progress bar” experiments all over CodePen. Well, I’m not exactly “green” on the topic; we’ve published a handful of articles on it including this neat-o one by Lee Meyer published the other week.

Our “oldest” article about the feature is by Bramus, dated back to July 2021. We were calling it “scroll-linked” animation back then. I specifically mention Bramus because there’s no one else working as hard as he is to discover practical use cases where scroll-driven animations shine while helping everyone understand the concept. He writes about it exhaustively on his personal blog in addition to writing the Chrome for Developers documentation on it.

But there’s also this free course he calls “Unleash the Power of Scroll-Driven Animations” published on YouTube as a series of 10 short videos. I decided it was high time to sit, watch, and learn from one of the best. These are my notes from it.

Introduction
  • A scroll-driven animation is an animation that responds to scrolling. There’s a direct link between scrolling progress and the animation’s progress.
  • Scroll-driven animations are different than scroll-triggered animations, which execute on scroll and run in their entirety. Scroll-driven animations pause, play, and run with the direction of the scroll. It sounds to me like scroll-triggered animations are a lot like the CSS version of the JavaScript intersection observer that fires and plays independently of scroll.
  • Why learn this? It’s super easy to take an existing CSS animation or a WAAPI animation and link it up to scrolling. The only “new” thing to learn is how to attach an animation to scrolling. Plus, hey, it’s the platform!
  • There are also performance perks. JavsScript libraries that establish scroll-driven animations typically respond to scroll events on the main thread, which is render-blocking… and JANK! We’re working with hardware-accelerated animations… and NO JANK. Yuriko Hirota has a case study on the performance of scroll-driven animations published on the Chrome blog.
  • Supported in Chrome 115+. Can use @supports (animation-timeline: scroll()). However, I recently saw Bramus publish an update saying we need to look for animation-range support as well.
@supports ((animation-timeline: scroll()) and (animation-range: 0% 100%)) { /* Scroll-Driven Animations related styles go here */ /* This check excludes Firefox Nightly which only has a partial implementation at the moment of posting (mid-September 2024). */ }
  • Remember to use prefers-reduced-motion and be mindful of those who may not want them.
Video One Core Concepts: scroll() and ScrollTimeline

Let’s take an existing CSS animation.

@keyframes grow-progress { from { transform: scaleX(0); } to { transform: scaleX(1); } } #progress { animation: grow-progress 2s linear forwards; }

Translation: Start with no width and scale it to its full width. When applied, it takes two seconds to complete and moves with linear easing just in the forwards direction.

This just runs when the #progress element is rendered. Let’s attach it to scrolling.

  • animation-timeline: The timeline that controls the animation’s progress.
  • scroll(): Creates a new scroll timeline set up to track the nearest ancestor scroller in the block direction.
#progress { animation: grow-progress 2s linear forwards; animation-timeline: scroll(); }

That’s it! We’re linked up. Now we can remove the animation-duration value from the mix (or set it to auto):

#progress { animation: grow-progress linear forwards; animation-timeline: scroll(); }

Note that we’re unable to plop the animation-timeline property on the animation shorthand, at least for now. Bramus calls it a “reset-only sub-property of the shorthand” which is a new term to me. Its value gets reset when you use the shorthand the same way background-color is reset by background. That means the best practice is to declare animation-timeline after animation.

/* YEP! */ #progress { animation: grow-progress linear forwards; animation-timeline: scroll(); } /* NOPE! */ #progress { animation-timeline: scroll(); animation: grow-progress linear forwards; }

Let’s talk about the scroll() function. It creates an anonymous scroll timeline that “walks up” the ancestor tree from the target element to the nearest ancestor scroll. In this example, the nearest ancestor scroll is the :root element, which is tracked in the block direction.

We can name scroll timelines, but that’s in another video. For now, know that we can adjust which axis to track and which scroller to target in the scroll() function.

animation-timeline: scroll(<axis> <scroller>);
  • <axis>: The axis — be it block (default), inline, y, or x.
  • <scroller>: The scroll container element that defines the scroll position that influences the timeline’s progress, which can be nearest (default), root (the document), or self.

If the root element does not have an overflow, then the animation becomes inactive. WAAPI gives us a way to establish scroll timelines in JavaScript with ScrollTimeline.

const $progressbar = document.querySelector(#progress); $progressbar.style.transformOrigin = '0% 50%'; $progressbar.animate( { transform: ['scaleX(0)', 'scaleY()'], }, { fill: 'forwards', timeline: new ScrollTimeline({ source: document.documentElement, // root element // can control `axis` here as well }), } ) Video Two Core Concepts: view() and ViewTimeline

First, we oughta distinguish a scroll container from a scroll port. Overflow can be visible or clipped. Clipped could be scrolling.

Those two bordered boxes show how easy it is to conflate scrollports and scroll containers. The scrollport is the visible part and coincides with the scroll container’s padding-box. When a scrollbar is present, that plus the scroll container is the root scroller, or the scroll container.

A view timeline tracks the relative position of a subject within a scrollport. Now we’re getting into IntersectionObserver territory! So, for example, we can begin an animation on the scroll timeline when an element intersects with another, such as the target element intersecting the viewport, then it progresses with scrolling.

Bramus walks through an example of animating images in long-form content when they intersect with the viewport. First, a CSS animation to reveal an image from zero opacity to full opacity (with some added clipping).

@keyframes reveal { from { opacity: 0; clip-path: inset(45% 20% 45% 20%); } to { opacity: 1; clip-path: inset(0% 0% 0% 0%); } } .revealing-image { animation: reveal 1s linear both; }

This currently runs on the document’s timeline. In the last video, we used scroll() to register a scroll timeline. Now, let’s use the view() function to register a view timeline instead. This way, we’re responding to when a .revealing-image element is in, well, view.

.revealing-image { animation: reveal 1s linear both; /* Rember to declare the timeline after the shorthand */ animation-timeline: view(); }

At this point, however, the animation is nice but only completes when the element fully exits the viewport, meaning we don’t get to see the entire thing. There’s a recommended way to fix this that Bramus will cover in another video. For now, we’re speeding up the keyframes instead by completing the animation at the 50% mark.

@keyframes reveal { from { opacity: 0; clip-path: inset(45% 20% 45% 20%); } 50% { opacity: 1; clip-path: inset(0% 0% 0% 0%); } }

More on the view() function:

animation-timeline: view(<axis> <view-timeline-inset>);

We know <axis> from the scroll() function — it’s the same deal. The <view-timeline-inset> is a way of adjusting the visibility range of the view progress (what a mouthful!) that we can set to auto (default) or a <length-percentage>. A positive inset moves in an outward adjustment while a negative value moves in an inward adjustment. And notice that there is no <scroller> argument — a view timeline always tracks its subject’s nearest ancestor scroll container.

OK, moving on to adjusting things with ViewTimeline in JavaScript instead.

const $images = document.querySelectorAll(.revealing-image); $images.forEach(($image) => { $image.animate( [ { opacity: 0, clipPath: 'inset(45% 20% 45% 20%)', offset: 0 } { opacity: 1; clipPath: 'inset(0% 0% 0% 0%)', offset: 0.5 } ], { fill: 'both', timeline: new ViewTimeline({ subject: $image, axis: 'block', // Do we have to do this if it's the default? }), } } )

This has the same effect as the CSS-only approach with animation-timeline.

Video Three Timeline Ranges Demystified

Last time, we adjusted where the image’s reveal animation ends by tweaking the keyframes to end at 50% rather than 100%. We could have played with the inset(). But there is an easier way: adjust the animation attachment range,

Most scroll animations go from zero scroll to 100% scroll. The animation-range property adjusts that:

animation-range: normal normal;

Those two values: the start scroll and end scroll, default:

animation-range: 0% 100%;

Other length units, of course:

animation-range: 100px 80vh;

The example we’re looking at is a “full-height cover card to fixed header”. Mouthful! But it’s neat, going from an immersive full-page header to a thin, fixed header while scrolling down the page.

@keyframes sticky-header { from { background-position: 50% 0; height: 100vh; font-size: calc(4vw + 1em); } to { background-position: 50% 100%; height: 10vh; font-size: calc(4vw + 1em); background-color: #0b1584; } }

If we run the animation during scroll, it takes the full animation range, 0%-100%.

.sticky-header { position: fixed; top: 0; animation: sticky-header linear forwards; animation-timeline: scroll(); }

Like the revealing images from the last video, we want the animation range a little narrower to prevent the header from animating out of view. Last time, we adjusted the keyframes. This time, we’re going with the property approach:

.sticky-header { position: fixed; top: 0; animation: sticky-header linear forwards; animation-timeline: scroll(); animation-range: 0vh 90vh; }

We had to subtract the full height (100vh) from the header’s eventual height (10vh) to get that 90vh value. I can’t believe this is happening in CSS and not JavaScript! Bramus sagely notes that font-size animation happens on the main thread — it is not hardware-accelerated — and the entire scroll-driven animation runs on the main as a result. Other properties cause this as well, notably custom properties.

Back to the animation range. It can be diagrammed like this:

The animation “cover range”. The dashed area represents the height of the animated target element.

Notice that there are four points in there. We’ve only been chatting about the “start edge” and “end edge” up to this point, but the range covers a larger area in view timelines. So, this:

animation-range: 0% 100%; /* same as 'normal normal' */

…to this:

animation-range: cover 0% cover 100%; /* 'cover normal cover normal' */

…which is really this:

animation-range: cover;

So, yeah. That revealing image animation from the last video? We could have done this, rather than fuss with the keyframes or insets:

animation-range: cover 0% cover 50%;

So nice. The demo visualization is hosted at scroll-driven-animations.style. Oh, and we have keyword values available: contain, entry, exit, entry-crossing, and exit-crossing.

contain entry exit

The examples so far are based on the scroller being the root element. What about ranges that are taller than the scrollport subject? The ranges become slightly different.

Just have to be aware of the element’s size and how it impacts the scrollport.

This is where the entry-crossing and entry-exit values come into play. This is a little mind-bendy at first, but I’m sure it’ll get easier with use. It’s clear things can get complex really quickly… which is especially true when we start working with multiple scroll-driven animation with their own animation ranges. Yes, that’s all possible. It’s all good as long as the ranges don’t overlap. Bramus uses a contact list demo where contact items animate when they enter and exit the scrollport.

@keyframes animate-in { 0% { opacity: 0; transform: translateY: 100%; } 100% { opacity: 1; transform: translateY: 0%; } } @keyframes animate-out { 0% { opacity: 1; transform: translateY: 0%; } 100% { opacity: 0; transform: translateY: 100%; } } .list-view li { animation: animate-in linear forwards, animate-out linear forwards; animation-timeline: view(); animation-range: entry, exit; /* animation-in, animation-out */ }

Another way, using entry and exit keywords directly in the keyframes:

@keyframes animate-in { entry 0% { opacity: 0; transform: translateY: 100%; } entry 100% { opacity: 1; transform: translateY: 0%; } } @keyframes animate-out { exit 0% { opacity: 1; transform: translateY: 0%; } exit 100% { opacity: 0; transform: translateY: 100%; } } .list-view li { animation: animate-in linear forwards, animate-out linear forwards; animation-timeline: view(); }

Notice that animation-range is no longer needed since its values are declared in the keyframes. Wow.

OK, ranges in JavaScript.:

const timeline = new ViewTimeline({ subjext: $li, axis: 'block', }) // Animate in $li.animate({ opacity: [ 0, 1 ], transform: [ 'translateY(100%)', 'translateY(0)' ], }, { fill: 'forwards', // One timeline instance with multiple ranges timeline, rangeStart: 'entry: 0%', rangeEnd: 'entry 100%', }) Video Four Core Concepts: Timeline Lookup and Named Timelines

This time, we’re learning how to attach an animation to any scroll container on the page without needing to be an ancestor of that element. That’s all about named timelines.

But first, anonymous timelines track their nearest ancestor scroll container.

<html> <!-- scroll --> <body> <div class="wrapper"> <div style="animation-timeline: scroll();"></div> </div> </body> </html>

Some problems might happen like when overflow is hidden from a container:

<html> <!-- scroll --> <body> <div class="wrapper" style="overflow: hidden;"> <!-- scroll --> <div style="animation-timeline: scroll();"></div> </div> </body> </html>

Hiding overflow means that the element’s content block is clipped to its padding box and does not provide any scrolling interface. However, the content must still be scrollable programmatically meaning this is still a scroll container. That’s an easy gotcha if there ever was one! The better route is to use overflow: clipped rather than hidden because that prevents the element from becoming a scroll container.

Hiding oveflow = scroll container. Clipping overflow = no scroll container. Bramus says he no longer sees any need to use overflow: hidden these days unless you explicitly need to set a scroll container. I might need to change my muscle memory to make that my go-to for hiding clipping overflow.

Another funky thing to watch for: absolute positioning on a scroll animation target in a relatively-positioned container. It will never match an outside scroll container that is scroll(inline-nearest) since it is absolute to its container like it’s unable to see out of it.

We don’t have to rely on the “nearest” scroll container or fuss with different overflow values. We can set which container to track with named timelines.

.gallery { position: relative; } .gallery__scrollcontainer { overflow-x: scroll; scroll-timeline-name: --gallery__scrollcontainer; scroll-timeline-axis: inline; /* container scrolls in the inline direction */ } .gallery__progress { position: absolute; animation: progress linear forwards; animation-timeline: scroll(inline nearest); }

We can shorten that up with the scroll-timeline shorthand:

.gallery { position: relative; } .gallery__scrollcontainer { overflow-x: scroll; scroll-timeline: --gallery__scrollcontainer inline; } .gallery__progress { position: absolute; animation: progress linear forwards; animation-timeline: scroll(inline nearest); }

Note that block is the scroll-timeline-axis initial value. Also, note that the named timeline is a dashed-ident, so it looks like a CSS variable.

That’s named scroll timelines. The same is true of named view timlines.

.scroll-container { view-timeline-name: --card; view-timeline-axis: inline; view-timeline-inset: auto; /* view-timeline: --card inline auto */ }

Bramus showed a demo that recreates Apple’s old cover-flow pattern. It runs two animations, one for rotating images and one for setting an image’s z-index. We can attach both animations to the same view timeline. So, we go from tracking the nearest scroll container for each element in the scroll:

.covers li { view-timeline-name: --li-in-and-out-of-view; view-timeline-axis: inline; animation: adjust-z-index linear both; animation-timeline: view(inline); } .cards li > img { animation: rotate-cover linear both; animation-timeline: view(inline); }

…and simply reference the same named timelines:

.covers li { view-timeline-name: --li-in-and-out-of-view; view-timeline-axis: inline; animation: adjust-z-index linear both; animation-timeline: --li-in-and-out-of-view;; } .cards li > img { animation: rotate-cover linear both; animation-timeline: --li-in-and-out-of-view;; }

In this specific demo, the images rotate and scale but the updated sizing does not affect the view timeline: it stays the same size, respecting the original box size rather than flexing with the changes.

Phew, we have another tool for attaching animations to timelines that are not direct ancestors: timeline-scope.

timeline-scope: --example;

This goes on an parent element that is shared by both the animated target and the animated timeline. This way, we can still attach them even if they are not direct ancestors.

<div style="timeline-scope: --gallery"> <div style="scroll-timeline: --gallery-inline;"> ... </div> <div style="animation-timeline: --gallery;"></div> </div>

It accepts multiple comma-separated values:

timeline-scope: --one, --two, --three; /* or */ timeline-scope: all; /* Chrome 116+ */

There’s no Safari or Firefox support for the all kewword just yet but we can watch for it at Caniuse (or the newer BCD Watch!).

This video is considered the last one in the series of “core concepts.” The next five are more focused on use cases and examples.

Video Five Add Scroll Shadows to a Scroll Container

In this example, we’re conditionally showing scroll shadows on a scroll container. Chris calls scroll shadows one his favorite CSS-Tricks of all time and we can nail them with scroll animations.

Here is the demo Chris put together a few years ago:

CodePen Embed Fallback

That relies on having a background with multiple CSS gradients that are pinned to the extremes with background-attachment: fixed on a single selector. Let’s modernize this, starting with a different approach using pseudos with sticky positioning:

.container::before, .container::after { content: ""; display: block; position: sticky; left: 0em; right 0em; height: 0.75rem; &::before { top: 0; background: radial-gradient(...); } &::after { bottom: 0; background: radial-gradient(...); } }

The shadows fade in and out with a CSS animation:

@keyframes reveal { 0% { opacity: 0; } 100% { opacity: 1; } } .container { overflow:-y auto; scroll-timeline: --scroll-timeline block; /* do we need `block`? */ &::before, &::after { animation: reveal linear both; animation-timeline: --scroll-timeline; } }

This example rocks a named timeline, but Bramus notes that an anonymous one would work here as well. Seems like anonymous timelines are somewhat fragile and named timelines are a good defensive strategy.

The next thing we need is to set the animation’s range so that each pseudo scrolls in where needed. Calculating the range from the top is fairly straightforward:

.container::before { animation-range: 1em 2em; }

The bottom is a little tricker. It should start when there are 2em of scrolling and then only travel for 1em. We can simply reverse the animation and add a little calculation to set the range based on it’s bottom edge.

.container::after { animation-direction: reverse; animation-range: calc(100% - 2em) calc(100% - 1em); }

Still one more thing. We only want the shadows to reveal when we’re in a scroll container. If, for example, the box is taller than the content, there is no scrolling, yet we get both shadows.

This is where the conditional part comes in. We can detect whether an element is scrollable and react to it. Bramus is talking about an animation keyword that’s new to me: detect-scroll.

@keyframes detect-scroll { from, to { --can-scroll: ; /* value is a single space and acts as boolean */ } } .container { animation: detect-scroll; animation-timeline: --scroll-timeline; animation-fill-mode: none; }

Gonna have to wrap my head around this… but the general idea is that --can-scroll is a boolean value we can use to set visibility on the pseudos:

.content::before, .content::after { --vis-if-can-scroll: var(--can-scroll) visible; --vis-if-cant-scroll: hidden; visibility: var(--vis-if-can-scroll, var(--vis-if-cant-scroll)); }

Bramus points to this CSS-Tricks article for more on the conditional toggle stuff.

Video Six Animate Elements in Different Directions

This should be fun! Let’s say we have a set of columns:

<div class="columns"> <div class="column reverse">...</div> <div class="column">...</div> <div class="column reverse">...</div> </div>

The goal is getting the two outer reverse columns to scroll in the opposite direction as the inner column scrolls in the other direction. Classic JavaScript territory!

The columns are set up in a grid container. The columns flex in the column direction.

/* run if the browser supports it */ @supports (animation-timeline: scroll()) { .column-reverse { transform: translateY(calc(-100% + 100vh)); flex-direction: column-reverse; /* flows in reverse order */ } .columns { overflow-y: clip; /* not a scroll container! */ } }

First, the outer columns are pushed all the way up so the bottom edges are aligned with the viewport’s top edge. Then, on scroll, the outer columns slide down until their top edges re aligned with the viewport’s bottom edge.

The CSS animation:

@keyframes adjust-position { from /* the top */ { transform: translateY(calc(-100% + 100vh)); } to /* the bottom */ { transform: translateY(calc(100% - 100vh)); } } .column-reverse { animation: adjust-position linear forwards; animation-timeline: scroll(root block); /* viewport in block direction */ }

The approach is similar in JavaScript:

const timeline = new ScrollTimeline({ source: document.documentElement, }); document.querySelectorAll(".column-reverse").forEach($column) => { $column.animate( { transform: [ "translateY(calc(-100% + 100vh))", "translateY(calc(100% - 100vh))" ] }, { fill: "both", timeline, } ); } Video Seven Animate 3D Models and More on Scroll

This one’s working with a custom element for a 3D model:

<model-viewer alt="Robot" src="robot.glb"></model-viewer>

First, the scroll-driven animation. We’re attaching an animation to the component but not defining the keyframes just yet.

@keyframes foo { } model-viewer { animation: foo linear both; animation-timeline: scroll(block root); /* root scroller in block direction */ }

There’s some JavaScript for the full rotation and orientation:

// Bramus made a little helper for handling the requested animation frames import { trackProgress } from "https://esm.sh/@bramus/sda-utilities"; // Select the component const $model = document.QuerySelector("model-viewer"); // Animation begins with the first iteration const animation = $model.getAnimations()[0]; // Variable to get the animation's timing info let progress = animation.effect.getComputedTiming().progress * 1; // If when finished, $progress = 1 if (animation.playState === "finished") progress = 1; progress = Math.max(0.0, Math.min(1.0, progress)).toFixed(2); // Convert this to degrees $model.orientation = `0deg 0deg $(progress * -360)deg`;

We’re using the effect to get the animation’s progress rather than the current timed spot. The current time value is always measured relative to the full range, so we need the effect to get the progress based on the applied animation.

Video Eight Scroll Velocity Detection

The video description is helpful:

Bramus goes full experimental and uses Scroll-Driven Animations to detect the active scroll speed and the directionality of scroll. Detecting this allows you to style an element based on whether the user is scrolling (or not scrolling), the direction they are scrolling in, and the speed they are scrolling with … and this all using only CSS.

First off, this is a hack. What we’re looking at is expermental and not very performant. We want to detect the animations’s velocity and direction. We start with two custom properties.

@keyframes adjust-pos { from { --scroll-position: 0; --scroll-position-delayed: 0; } to { --scroll-position: 1; --scroll-position-delayed: 1; } } :root { animation: adjust-pos linear both; animation-timeline: scroll(root); }

Let’s register those custom properties so we can interpolate the values:

@property --scroll-position { syntax: "<number>"; inherits: true; initial-value: 0; } @property --scroll-position-delayed { syntax: "<number>"; inherits: true; initial-value: 0; }

As we scroll, those values change. If we add a little delay, then we can stagger things a bit:

:root { animation: adjust-pos linear both; animation-timeline: scroll(root); } body { transition: --scroll-position-delayed 0.15s linear; }

The fact that we’re applying this to the body is part of the trick because it depends on the parent-child relationship between html and body. The parent element updates the values immediately while the child lags behind just a tad. The evaluate to the same value, but one is slower to start.

We can use the difference between the two values as they are staggered to get the velocity.

:root { animation: adjust-pos linear both; animation-timeline: scroll(root); } body { transition: --scroll-position-delayed 0.15s linear; --scroll-velocity: calc( var(--scroll-position) - var(--scroll-position-delayed) ); }

Clever! If --scroll-velocity is equal to 0, then we know that the user is not scrolling because the two values are in sync. A positive number indicates the scroll direction is down, while a negative number indicates scrolling up,.

There’s a little discrepancy when scrolling abruptly changes direction. We can fix this by tighening the transition delay of --scroll-position-delayed but then we’re increasing the velocity. We might need a multiplier to further correct that… that’s why this is a hack. But now we have a way to sniff the scrolling speed and direction!

Here’s the hack using math functions:

body { transition: --scroll-position-delayed 0.15s linear; --scroll-velocity: calc( var(--scroll-position) - var(--scroll-position-delayed) ); --scroll-direction: sign(var(--scroll-velocity)); --scroll-speed: abs(var(--scroll-velocity)); }

This is a little funny because I’m seeing that Chrome does not yet support sign() or abs(), at least at the time I’m watching this. Gotta enable chrome://flags. There’s a polyfill for the math brought to you by Ana Tudor right here on CSS-Tricks.

So, now we could theoretically do something like skew an element by a certain amount or give it a certain level of background color saturation depending on the scroll speed.

.box { transform: skew(calc(var(--scroll-velocity) * -25deg)); transition: background 0.15s ease; background: hsl( calc(0deg + (145deg * var(--scroll-direction))) 50 % 50% ); }

We could do all this with style queries should we want to:

@container style(--scroll-direction: 0) { /* idle */ .slider-item { background: crimson; } } @container style(--scroll-direction: 1) { /* scrolling down */ .slider-item { background: forestgreen; } } @container style(--scroll-direction: -1) { /* scrolling down */ .slider-item { background: lightskyblue; } }

Custom properties, scroll-driven animations, and style queries — all in one demo! These are wild times for CSS, tell ya what.

Video Nine Outro

The tenth and final video! Just a summary of the series, so no new notes here. But here’s a great demo to cap it off.

CodePen Embed Fallback Video Ten

Unleash the Power of Scroll-Driven Animations originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Combining forces, GSAP & Webflow!

Css Tricks - Fri, 10/18/2024 - 3:09am

Change can certainly be scary whenever a beloved, independent software library becomes a part of a larger organization. I’m feeling a bit more excitement than concern this time around, though.

If you haven’t heard, GSAP (GreenSock Animation Platform) is teaming up with the visual website builder, Webflow. This mutually beneficial advancement not only brings GSAP’s powerful animation capabilities to Webflow’s graphical user interface but also provides the GSAP team the resources necessary to take development to the next level.

GSAP has been independent software for nearly 15 years (since the Flash and ActionScript days!) primarily supported by Club GSAP memberships, their paid tiers which offer even more tools and plugins to enhance GSAP further. GSAP is currently used on more than 12 million websites.

I chatted with Cassie Evans — GSAP’s Lead Bestower of Animation Superpowers and CSS-Tricks contributor — who confidently expressed that GSAP will remain available for the wider web.

It’s a big change, but we think it’s going to be a good one – more resources for the core library, more people maintaining the GSAP codebase, money for events and merch and community support, a VISUAL GUI in the pipeline.

The Webflow community has cause for celebration as well, as direct integration with GSAP has been a wishlist item for a while.

The webflow community is so lovely and creative and supportive and friendly too. It’s a good fit.

I’m so happy for Jack, Cassie, and Rodrigo, as well as super excited to see what happens next. If you don’t want to take my word for it, check out what Brody has to say about it.

Combining forces, GSAP & Webflow! originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Mastering theme.json: You might not need CSS

Css Tricks - Fri, 10/18/2024 - 1:36am

I totally get the goal here: make CSS more modular and scalable in WordPress. Put all your global WordPress theme styles in a single file, including variations. JSON offers a nicely structured syntax that’s easily consumable by JavaScript, thereby allowing the sweet affordance of loading exactly what we want when we want it.

The problem, to me, is that writing “CSS” in a theme.json file is a complete mental model switcher-oo. Rather than selectors, we have a whole set of objects we have to know about just to select something. We have JSON properties that look and feel like CSS properties, only they have to be camelCased being JavaScript and all. And we’re configuring features in the middle of the styles, meaning we’ve lost a clear separation of concerns.

I’m playing devil’s advocate, of course. There’s a lot of upside to abstracting CSS with JSON for the very niche purpose of theming CMS templates and components. But after a decade of “CSS-in-JS is the Way™” I’m less inclined to buy into it. CSS is the bee’s knees just the way it is and I’m OK relying on it solely, whether it’s in the required style.css file or some other plain ol’ CSS file I generate. But that also means I’m losing out on the WordPress features that require you to write styles in a theme.json file, like style variations that can be toggled directly in the WordPress admin.

Regardless of all that, I’m linking this up because Justin does bang-up work (no surprise, really) explaining and illustrating the ways of CSS-in-WordPress. We have a complete guide that Ganesh rocked a couple of years ago. You might check that to get familiar with some terminology, jump into a nerdy deep dive on how WordPress generates classes from JSON, or just use the reference tables as a cheat sheet.

Mastering theme.json: You might not need CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Solving Background Overflow With Inherited Border Radii

Css Tricks - Thu, 10/17/2024 - 5:24am

One of the interesting (but annoying) things about CSS is the background of children’s elements can bleed out of the border radius of the parent element. Here’s an example of a card with an inner element. If the inner element is given a background, it can bleed out of the card’s border.

CodePen Embed Fallback

The easiest way to resolve this problem is to add overflow: hidden to the card element. I’m sure that’s the go-to solution most of us reach for when this happens.

But doing this creates a new problem — content outside the card element gets clipped off — so you can’t use negative margins or position: absolute to shift the children’s content out of the card.

CodePen Embed Fallback

There is a slightly more tedious — but more effective — way to prevent a child’s background from bleeding out of the parent’s border-radius. And that is to add the same border-radius to the child element.

The easiest way to do this is allowing the child to inherit the parent’s border-radius:

.child { border-radius: inherit; } CodePen Embed Fallback

If the border-radius shorthand is too much, you can still inherit the radius for each of the four corners on a case-by-case basis:

.child { border-top-left-radius: inherit; border-top-right-radius: inherit; border-bottom-left-radius: inherit; border-bottom-right-radius: inherit; }

Or, for those of you who’re willing to use logical properties, here’s the equivalent. (For an easier way to understand logical properties, replace top and left with start, and bottom and right with end.)

.child { border-start-start-radius: inherit; border-top-end-radius: inherit; border-end-start-radius: inherit; border-end-end-radius: inherit; } Can’t we just apply a background on the card?

If you have a background directly on the .card that contains the border-radius, you will achieve the same effect. So, why not?

CodePen Embed Fallback

Well, sometimes you can’t do that. One situation is when you have a .card that’s split into two, and only one part is colored in.

CodePen Embed Fallback So, why should we do this?

Peace of mind is probably the best reason. At the very least, you know you won’t be creating problems down the road with the radius manipulation solution.

This pattern is going to be especially helpful when CSS Anchor Positioning gains full support. I expect that would become the norm popover positioning soon in about 1-2 years.

That said, for popovers, I personally prefer to move the popover content out of the document flow and into the <body> element as a direct descendant. By doing this, I prevent overflow: hidden from cutting off any of my popovers when I use anchor positioning.

Solving Background Overflow With Inherited Border Radii originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Close, Exit, Cancel: How to End User Interactions Well

Css Tricks - Wed, 10/16/2024 - 4:12am

What’s in a word? Actions. In the realm of user interfaces, a word is construed as the telltale of a control’s action. Sometimes it points us in the correct direction, and sometimes it leads us astray. We talk a lot about semantics in front-end web development, but outside of code, semantics are at the heart of copywriting where each word we convey can mean different things to different people. Words, if done right, add clarity and direction.

As a web user, I’ve come across words in user interfaces that have misled me. And not necessarily by design, either. Some words are synonymous with others and their true meaning depends entirely on context. Some words are easy to mistake for an unintended meaning because they are packed with so much meaning. A word might belong to a fellowship of interchangeable words.

Although I’m quite riled up when I misread content on a page — upset at the lack of clarity more than anything — as a developer, I can’t say I’ve always chosen the best possible words or combination of words for all the user interfaces I’ve ever made. But experience, both as a user and a developer, has elevated my commonsense when it comes to some of the literary choices I make while coding.

This article covers the words I choose for endings, to help users move away, and move on, without any confusion from the current process they are at on the screen. I went down this rabbit hole because I often find that ending something can mean many things — whether it be canceling an action, quitting an application, closing an element, navigating back, exiting a chat interaction… You get the idea. There are many ways to say that something is done, complete, and ready to move on to something else. I want to add clarity to that.

Getting Canceled

If there’s a Hall of Fame for button labels, this is the Babe Ruth of them all. “Cancel” is a widely used word to indicate an action that ends something. Cancel is a sharp, tenacious action. The person wants to bail on some process that didn’t go the way they expected it to. Maybe the page reveals a form that the person didn’t realize would be so long, so they want to back off. It could be something you have no control over whatsoever, like that person realizing they do not have their credit card information handy during checkout and they have to come back another time.

Cancel can feel personal at times, right? Don’t like the shipping costs calculated at checkout? Cancel the payment. Don’t like the newsletter? Cancel The Subscription. But really, the person only wants to undo an incorrect action or decision leaving no trace of it behind in favor of a clean slate to try again… or not.

The only times I feel betrayed by the word cancel is when the process I’m trying to end continues anyway. That comes up most when submitting forms with incorrect information. I enter something inadvertently, hit a big red Cancel button, yet the information I’ve “saved” persists to the extent that I either need to contact customer support or start looking for alternatives.

That’s the bottom line: Use “cancel” as an opportunity to confirm. It’s the person telling you, “Hey, that’s not actually what I meant to do,” and you get to step in and be the hero to wipe the mistake clean and set things up for a second chance. We’re not technically “ending” anything but rather starting clean and picking things back up for a better go. Think about that the next time you find yourself needing a label that encourages the user to try again. You might even consider synonyms that are less closely associated with closed endings, such as reset or retry.

Quitting or Exiting?

Quit window, quit tab, quit app — now we’re talking about finality. When we “quit” or “exit” something, we’re changing course. We’ve made progress in one direction and decide it’s time to chart a different path. If we’re thinking about it in terms of freeway traffic, you might say that “quitting” is akin to pulling over and killing the engine, and “exiting” is taking leaving the freeway for another road. There’s a difference, although the two terms are closely related.

As far as we’re concerned as developers, quit and exit are hard stop points in an application. It’s been put to rest. Nothing else beyond this should be possible except its rebirth when the service is restarted or reopened. So, if your page is capable of nuking the current experience and the user takes it, then quit is the better label to make that point. We’re quitting and have no plans to restart or re-engage. If you were to “quit” your job, it’s not like your employer is expecting you to report for duty on Monday… or any other day for that matter.

But here’s my general advice about the word quit: only use it if you have to. I see very few use cases where we actually want to offer someone a true way to quit something. It’s so effective at conveying finality in web interfaces that it shuts the door on any future actions. For instance, I find that cancel often works in its place. And, personally, I find that saying “cancel payment” is more widely applicable. It’s softer and less rigid in the sense that it leaves the possibility to resume a process down the road.

Quit is also a simple process. Just clear everything and be gone. But if quitting means the user might lose some valuable data or progress, then that’s something they have to be warned about. In that case, exit and save may be better guidance.

I consider Exit the gentler twin of Quit. I prefer Quit just for the ultimatum of it. I see Exit used less frequently in interfaces than I see Quit. In rare cases, I might see Exit used specifically because of its softer nature to Quit even though “quitting” is the correct semantic choice given that the user really wants to wipe things clean and the assurance that nothing is left behind. Sometimes a “tougher” term is more reassuring.

Exit, however, is an excellent choice for actions that represent the end of human-to-human interactions — things like Exit Group, Exit Chat, Exit Streaming, Exit Class. If this person is kindly saying goodbye to someone or something but open to future interactions, allow them to exit when they’re done. They’re not quitting anything and we aren’t shoving them out the door.

Going Back (and Forth)

Let’s talk about navigation. That’s the way we describe moving around the internet. We navigate from one place to another, to another, to another, and so on. It’s a journey of putting one digital foot in front of the other on the way to somewhere. That journey comes to an end when we get to our destination… or when we “quit” or “exit” the journey as we discussed above.

But the journey may take twists and turns. Not all movement is linear on the web. That’s why we often leave breadcrumbs in interfaces, right? It’s wayfinding on the web and provides people with a way to go “back” where they came from. Maybe that person forgot a step and needs to head back in order to move forward again.

In other words, back displaces people — laterally and hierarchically. Laterally, back (and its synonym, previous), backtracks across the same level in a process, for instance, between two sections of the same form, or two pages of the same document. Hierarchically, back — not to mention more explicit variants like “home” — is a level above that in the navigation hierarchy.

I like the explicit nature of saying something like “Home” when it comes to navigating someone “back” to a location or state. There’s no ambiguity there: hey, let’s go back home. Being explicit opens you up to more verbose labels but brevity isn’t always the goal. Even in iconography, adding more detail to a visual can help add clarity. The same is true with content in user interfaces. My favorite example is the classic “Back to Top” button on many pages that navigate you to the “top” of the page. We’re going “back to the top” which would not have been clear if we had used “Back” alone. Back where? That’s an important question — particularly when working with in-page anchors — and the answer may not be as obvious to others as it is to you. Communicating that level of hierarchy explicitly is a navigational feature.

While the “Back to Top” example I gave is a better illustration of lateral displacement than hierarchical displacement, I tend to avoid the label back with any sort of lateral navigation because moving laterally typically involves navigating between states more than navigating between pages. For example, the user may be navigating from a “logged in” state to a “logged out” state. In this case, I prefer being even more explicit — e.g., Save and Go Back, or Cancel and Go Home — than hierarchical navigation because we’re changing states on top of moving away from something.

Closing Down

Close is yet another term you’ll find in the wild for conveying the “end” of something. It’s quite similar to Back in the sense that it serves dual purposes. It can be for navigation — close the current page and go back — or it can be for canceling an action — close the current page, and either discard or save all the data entered so far.

I prefer Close for neither of those cases. If we’re in the context of navigation, I like the clarity of the more explicit guidance we discussed above, e.g., Go Back, Previous, or Go Home. Giving someone an instruction to Close doesn’t say where that person is going to land once navigating away from the current page. And if we’re dealing with actions, Save and Close affirms the person that their data will be saved, rather than simply “closing” it out. If we were to simply say “cancel” instead, the insinuation is that the user is quitting the action and can expect to lose their work.

The one time I do feel that “Close” is the ideal label is working with pop-up dialogues and modals. Placing “Close” at the top-right (or the block-start, inline-end edge if we’re talking logical directions) corner is more than clear enough about what happens to the pop-up or modal when clicking it. We can afford to be a little less explicit with our semantics when someone’s focus is trapped in a specific context.

The End.

I’ve saved the best for last, right? There’s no better way to connote an ending than simply calling it the “end”. It works well when we pair it with what’s ending.

End Chat. End Stream. End Webinar.

You’re terminating an established connection, not with a process, but with a human. And this is not some abrupt termination like Quit or Cancel. It’s more of a proper goodbye. Consider it also a synonym to Exit because the person ending the interaction may simply be taking a break. They’re not necessarily quitting something for good. Let’s leave the light on the front patio for them to return later and pick things back up..

And speaking of end, we’ve reached the end of this article. That’s the tricky, but liberating, thing about content semantics — some words may technically be correct but still mislead site visitors. It’s not that we’re ever trying to give someone bad directions, but it can still happen because this is a world where there are many ways of saying the same thing. Our goal is to be unambiguous and the milestone is clarity. Settling on the right word or combination of words takes effort. Anyone who has struggled with naming things in code knows about this. It’s the same for naming things outside of code.

I did not make an attempt to cover each and every word or way to convey endings. The point is that our words matter and we have all the choice and freedom in the world to find the best fit. But maybe you’ve recently run into a situation where you needed to “end” something and communicate that in an interface. Did you rely on something definitive and permanent (e.g. quit) or did you find that softer language (e.g. exit) was the better direction? What other synonyms did you consider? I’d love to know!

End Article.

Close, Exit, Cancel: How to End User Interactions Well originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

CSS Tricks That Use Only One Gradient

Css Tricks - Fri, 10/11/2024 - 11:48am

CSS gradients have been so long that there’s no need to rehash what they are and how to use them. You have surely encountered them at some point in your front-end journey, and if you follow me, you also know that I use them all the time. I use them for CSS patterns, nice CSS decorations, and even CSS loaders. But even so, gradients have a tough syntax that can get very complicated very quickly if you’re not paying attention.

In this article, we are not going to make complex stuff with CSS gradients. Instead, we’re keeping things simple and I am going to walk through all of the incredible things we can do with just one gradient.

Only one gradient? In this case, reading the doc should be enough, no?

No, not really. Follow along and you will see that gradients are easy at their most basic, but are super powerful if we push them — or in this case, just one — to their limits.

CSS patterns

One of the first things you learn with gradients is that we can establish repeatable patterns with them. You’ve probably seen some examples of checkerboard patterns in the wild. That’s something we can quickly pull off with a single CSS gradient. In this case, we can reach for the repeating-conic-gradient() function:

background: repeating-conic-gradient(#000 0 25%, #fff 0 50%) 0 / 100px 100px;

A more verbose version of that without the background shorthand:

background-image: repeating-conic-gradient(#000 0 25%, #fff 0 50%); background-size: 100px 100px;

Either way, the result is the same:

CodePen Embed Fallback

Pretty simple so far, right? You have two colors that you can easily swap out for other colors, plus the background-size property to control the square shapes.

If we change the color stops — where one color stops and another starts — we get another cool pattern based on triangles:

background: repeating-conic-gradient(#000 0 12.5%, #fff 0 25%) 0 / 100px 100px; CodePen Embed Fallback

If you compare the CSS for the two demos we’ve seen so far, you’ll see that all I did was divide the color stops in half, 25% to 12.5% and 50% to 25%.

Another one? Let’s go!

CodePen Embed Fallback

This time I’m working with CSS variables. I like this because variables make it infinitely easier to configure the gradients by updating a few values without actually touching the syntax. The calculation is a little more complex this time around, as it relies on trigonometric functions to get accurate values.

I know what you are thinking: Trigonometry? That sounds hard. That is certainly true, particularly if you’re new to CSS gradients. A good way to visualize the pattern is to disable the repetition using the no-repeat value. This isolates the pattern to one instance so that you clearly see what’s getting repeated. The following example declares background-image without a background-size so you can see the tile that repeats and better understand each gradient:

CodePen Embed Fallback

I want to avoid a step-by-step tutorial for each and every example we’re covering so that I can share lots more examples without getting lost in the weeds. Instead, I’ll point you to three articles you can refer to that get into those weeds and allow you to pick apart our examples.

I’ll also encourage you to open my online collection of patterns for even more examples. Most of the examples are made with multiple gradients, but there are plenty that use only one. The goal of this article is to learn a few “single gradient” tricks — but the ultimate goal is to be able to combine as many gradients as possible to create cool stuff!

Grid lines

Let’s start with the following example:

CodePen Embed Fallback

You might claim that this belongs under “Patterns” — and you are right! But let’s make it more flexible by adding variables for controlling the thickness and the total number of cells. In other words, let’s create a grid!

.grid-lines { --n: 3; /* number of rows */ --m: 5; /* number of columns */ --s: 80px; /* control the size of the grid */ --t: 2px; /* the thickness */ width: calc(var(--m)*var(--s) + var(--t)); height: calc(var(--n)*var(--s) + var(--t)); background: conic-gradient(from 90deg at var(--t) var(--t), #0000 25%, #000 0) 0 0/var(--s) var(--s); }

First of all, let’s isolate the gradient to better understand the repetition (like we did in the previous section).

CodePen Embed Fallback

One repetition will give us a horizontal and a vertical line. The size of the gradient is controlled by the variable --s, so we define the width and height as a multiplier to get as many lines as we want to establish the grid pattern.

What’s with “+ var(--t)” in the equation?

The grid winds up like this without it:

CodePen Embed Fallback

We are missing lines at the right and the bottom which is logical considering the gradient we are using. To fix this, the gradient needs to be repeated one more time, but not at full size. For this reason, we are adding the thickness to the equation to have enough space for the extra repetition and the get the missing lines.

CodePen Embed Fallback

And what about a responsive configuration where the number of columns depends on the available space? We remove the --m variable and define the width like this:

width: calc(round(down, 100%, var(--s)) + var(--t));

Instead of multiplying things, we use the round() function to tell the browser to make the element full width and round the value to be a multiple of --s. In other words, the browser will find the multiplier for us!

Resize the below and see how the grid behaves:

CodePen Embed Fallback

In the future, we will also be able to do this with the calc-size() function:

width: calc-size(auto, round(down, size, var(--s)) + var(--t));

Using calc-size() is essentially the same as the last example, but instead of using 100% we consider auto to be the width value. It’s still early to adopt such syntax. You can test the result in the latest version of Chrome at the time of this writing:

CodePen Embed Fallback Dashed lines

Let’s try something different: vertical (or horizontal) dashed lines where we can control everything.

.dashed-lines { --t: 2px; /* thickness of the lines */ --g: 50px; /* gap between lines */ --s: 12px; /* size of the dashes */ background: conic-gradient(at var(--t) 50%, #0000 75%, #000 0) var(--g)/calc(var(--g) + var(--t)) var(--s); } CodePen Embed Fallback

Can you figure out how it works? Here is a figure with hints:

Try creating the horizontal version on your own. Here’s a demo that shows how I tackled it, but give it a try before peeking at it.

What about a grid with dashed lines — is that possible?

Yes, but using two gradients instead of one. The code is published over at my collection of CSS shapes. And yes, the responsive behavior is there as well!

CodePen Embed Fallback Rainbow gradient

How would you create the following gradient in CSS?

You might start by picking as many color values along the rainbow as you can, then chaining them in a linear-gradient:

linear-gradient(90deg, red, yellow, green, /* etc. */, red);

Good idea, but it won’t get you all the way there. Plus, it requires you to juggle color stops and fuss with them until you get things just right.

There is a simpler solution. We can accomplish this with just one color!

background: linear-gradient(90deg in hsl longer hue, red 0 0);

I know, the syntax looks strange if you’re seeing the new color interpolation for the first time.

If I only declare this:

background: linear-gradient(90deg, red, red); /* or (90deg, red 0 0) */

…the browser creates a gradient that goes from red to red… red everywhere! When we set this “in hsl“, we’re changing the color space used for the interpolation between the colors:

background: linear-gradient(90deg in hsl, red, red);

Now, the browser will create a gradient that goes from red to red… this time using the HSL color space rather than the default RGB color space. Nothing changes visually… still see red everywhere.

The longer hue bit is what’s interesting. When we’re in the HSL color space, the hue channel’s value is an angle unit (e.g., 25deg). You can see the HSL color space as a circle where the angle defines the position of the color within that circle.

Since it’s a circle, we can move between two points using a “short” path or “long” path.

If we consider the same point (red in our case) it means that the “short” path contains only red and the “long” path runs into all the colors as it traverses the color space.

CodePen Embed Fallback

Adam Argyle published a very detailed guide on high-definition colors in CSS. I recommend reading it because you will find all the features we’re covering (this section in particular) to get more context on how everything comes together.

We can use the same technique to create a color wheel using a conic-gradient:

background: conic-gradient(in hsl longer hue,red 0 0); CodePen Embed Fallback

And while we are on the topic of CSS colors, I shared another fun trick that allows you to define an array of color values… yes, in CSS! And it only uses a single gradient as well.

Hover effects

Let’s do another exercise, this time working with hover effects. We tend to rely on pseudo-elements and extra elements when it comes to things like applying underlines and overlays on hover, and we tend to forget that gradients are equally, if not more, effective for getting the job done.

Case in point. Let’s use a single gradient to form an underline that slides on hover:

h3 { background: linear-gradient(#1095c1 0 0) no-repeat var(--p,0) 100%/var(--p, 0) .1em; transition: 0.4s, background-position 0s; } h3:hover { --p: 100%; } CodePen Embed Fallback

You likely would have used a pseudo-element for this, right? I think that’s probably how most people would approach it. It’s a viable solution but I find that using a gradient instead results in cleaner, more concise CSS.

You might be interested in another article I wrote for CSS-Tricks where I use the same technique to create a wide variety of cool hover effects.

CSS shapes

Creating shapes with gradients is my favorite thing to do in CSS. I’ve been doing it for what feels like forever and love it so much that I published a “Modern Guide for Making CSS Shapes” over at Smashing Magazine earlier this year. I hope you check it out not only to learn more tricks but to see just how many shapes we can create with such a small amount of code — many that rely only on a single CSS gradient.

Some of my favorites include zig-zag borders:

CodePen Embed Fallback

…and “scooped” corners:

CodePen Embed Fallback

…as well as sparkles:

CodePen Embed Fallback

…and common icons like the plus sign:

CodePen Embed Fallback

I won’t get into the details of creating these shapes to avoid making this article long and boring. Read the guide and visit my CSS Shape collection and you’ll have everything you need to make these, and more!

Border image tricks

Let’s do one more before we put a cap on this. Earlier this year, I discovered how awesome the CSS border-image property is for creating different kinds of decorations and shapes. And guess what? border-image limits us to using just one gradient, so we are obliged to follow that restriction.

Again, just one gradient and we get a bunch of fun results. I’ll drop in my favorites like I did in the last section. Starting with a gradient overlay:

CodePen Embed Fallback

We can use this technique for a full-width background:

CodePen Embed Fallback

…as well as heading dividers:

CodePen Embed Fallback

…and even ribbons:

CodePen Embed Fallback

All of these have traditionally required hacks, magic numbers, and other workarounds. It’s awesome to see modern CSS making things more effortless. Go read my article on this topic to find all the interesting stuff you can make using border-image.

Wrapping up

I hope you enjoyed this collection of “single-gradient” tricks. Most folks I know tend to use gradients to create, well, gradients. But as we’ve seen, they are more powerful and can be used for lots of other things, like drawing shapes.

I like to add a reminder at the end of an article like this that the goal is not to restrict yourself to using one gradient. You can use more! The goal is to get a better handle on how gradients work and push them in interesting ways — that, in turn, makes us better at writing CSS. So, go forth and experiment — I’d love to see what you make!

CSS Tricks That Use Only One Gradient originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

WPGraphQL Becomes a Canonical Plugin: My Move to Automattic

Css Tricks - Thu, 10/10/2024 - 4:00am

It’s always a gas when a good person doing good work gets a good deal. In this case, Jason’s viral WPGraphQL plugin has not only become a canonical WordPress plugin, but creator Jason Bahl is joining Automattic as well.

I’m linking this up because it’s notable for a few reasons:

Congrats, Jason! I didn’t know you were in Denver — maybe we’ll bump into each other and I can give you a well-deserved high-five. ✋

WPGraphQL Becomes a Canonical Plugin: My Move to Automattic originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

2024: More CSS At-Rules Than the Past Decade Combined

Css Tricks - Wed, 10/09/2024 - 4:10am

More times than I can count, while writing, I get myself into random but interesting topics with little relation to the original post. In the end, I have to make the simple but painful choice of deleting or archiving hours of research and writing because I know most people click on a post with a certain expectation of what they’ll get, and I know it isn’t me bombing them with unrelated rants about CSS.

This happened to me while working on Monday’s article about at-rules. All I did there was focus on a number of recipes to test browser support for CSS at-rules. In the process, I began to realize, geez we have so many new at-rules — I wonder how many of them are from this year alone. That’s the rabbit hole I found myself in once I wrapped up the article I was working on.

And guess what, my hunch was right: 2024 has brought more at-rules than an entire decade of CSS.

It all started when I asked myself why we got a selector() wrapper function for the @supports at-rule but are still waiting for an at-rule() version. I can’t pinpoint the exact reasoning there, but I’m certain there wasn’t much of a need to check the support of at-rules because, well, there weren’t that many of them — it’s just recently that we got a windfall of at-rules.

Some historical context

So, right around 1998 when the CSS 2 recommendation was released, @import and @page were the only at-rules that made it into the CSS spec. That’s pretty much how things remained until the CSS 2.1 recommendation in 2011 introduced @media. Of course, there were other at-rules like — @font-face, @namespace and @keyframes to name a few — that had already debuted in their own respective modules. By this time, CSS dropped semantic versioning, and the specification didn’t give a true picture of the whole, but rather individual modules organized by feature.

Random tangent: The last accepted consensus says we are at “CSS 3”, but that was a decade ago and some even say we should start getting into CSS 5. Wherever we are is beside the point, although it’s certainly a topic of discussion happening. Is it even useful to have a named version?

The @supports at-rule was released in 2011 in CSS Conditional Rules Module Level 3 — Levels 1 and 2 don’t formally exist but refer to the original CSS 1 and 2 recommendations. We didn’t actually get support for it in most browsers until 2015, and at that time, the existing at-rules already had widespread support. The @supports was only geared towards new properties and values, designed to test browser support for CSS features before attempting to apply styles.

The numbers

As of today, we have a grand total of 18 at-rules in CSS that are supported by at least one major browser. If we look at the year each at-rule was initially defined in a CSSWG Working Draft, we can see they all have been published at a fairly consistent rate:

If we check the number of at-rules supported on each browser per year, however, we can see the massive difference in browser activity:

If we just focus on the last year a major browser shipped each at-rule, we will notice that 2024 has brought us a whopping seven at-rules to date!

Data collected from caniuse.

I like little thought experiments like this. Something you’re researching leads to researching about the same topic; out of scope, but tangentially related. It may not be the sort of thing you bookmark and reference daily, but it is good cocktail chatter. If nothing else, it’s affirming the feeling that CSS is moving fast, like really fast in a way we haven’t seen since CSS 3 first landed.

It also adds context for the CSS features we have — and don’t have. There was no at-rule() function initially because there weren’t many at-rules to begin with. Now that we’ve exploded with more new at-rules than the past decade combined, it may be no coincidence that just last week the Chrome Team updated the function’s status from New to Assigned!

One last note: the reason I’m even thinking about at-rules at all is that we’ve updated the CSS Almanac, expanding it to include more CSS features including at-rules. I’m trying to fill it up and you can always help by becoming a guest writer.

2024: More CSS At-Rules Than the Past Decade Combined originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Smashing Hour With Heydon Pickering

Css Tricks - Tue, 10/08/2024 - 5:22am

I sat down with Heydon Pickering in the most recent episode of the Smashing Hour. Full transparency: I was nervous as heck. I’ve admired Heydon’s work for years, and even though we run in similar circles, this was our first time meeting. You know how you build some things up in your mind and sorta psyche yourself out? Yeah, that.

Heydon is nothing short of a gentleman and, I’ll be darned, easy to talk to. As is the case with any Smashing Hour, there’s no script, no agenda, no nothing. We find ourselves getting into the weeds of accessibility testing and documentation — or the lack of it — before sliding into the stuff he’s really interested in and excited about today: styling sound. Dude pulled out a demo and walked me (and everyone else) through the basics of the Web Audio API and how he’s using it to visualize sounds in tons of groovy ways that I now want hooked up to my turntable somehow.

Smashing Hour With Heydon Pickering originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Smashing Conf: Is Atomic Design Dead?

LukeW - Mon, 10/07/2024 - 2:00pm

In his Is Atomic Design Dead? presentation at Smashing Conf New York, Brad Frost discussed the history of design systems and today's situation especially in light of very capable AI models than can generate code and designs. Here's my notes on his talk.

  • Websites started as HTML and CSS. People began to design websites in Photoshop and as the number of Web sites and apps increased, the need for managing a brand and style across multiple platforms became clear. To manage this people turned to frameworks and component libraries which resulted in more frameworks and tools that eventually got integrated into design tools like Figma. It's been an ongoing expansion...
  • There's been lots of change over the years but at the highest level, we have design systems and products that use them to enforce brand, consistency, accessibility, and more.
  • Compliance to design systems pushes from one side and product needs push from the other. There needs to be a balance but currently the gap between the two is growing. A good balance is achieved through a virtuous cycle between product and systems.
  • The atomic design system tried to intentionally define use of atoms, molecules, organisms, templates, and pages to bridge the gap between the end state of a product and a design system.
  • As an industry, we went too far in resourcing design systems and making them a standalone thing within a company. They've been isolated.
  • Design system makers can't be insular. They need to reach out to product teams and work with them. They need to be helping product teams achieve their goals.
  • What if there were one global design system with common reusable components? Isn't that what HTML is for? Yes, but it's insufficient because we're still rebuilding date pickers everywhere.
  • Open UI tracks popular design systems and what's in them. It's a start to seeing what global component needs for the Web could look like.
  • Many pattern libraries ship with an aesthetic and people need to tweak it. A global design system should be very vanilla so you can style it as much as you want.
  • The Web still has an amazing scale of communication and collaboration. We need to rekindle the ideas of the early Web. We need to share and build together to get to a common freely usable design system.
  • AI models can help facilitate design system work. Today they do an OK job but in the future, fine-tuned models may create custom components on the fly. They can also translate between one design system and another or translate across programming languages.
  • This methodology could help companies translate existing and legacy code to new modern design systems. Likewise sketches or mockups could be quickly translated directly to design system components thereby speeding up processes.
  • Combining design system specifications with large language models allows you to steer AI generations more directly toward the right kind of code and components.
  • When product experiences are more dynamic (can be built on the fly), can we adapt them to individual preferences and needs? Like custom styles or interactions.
  • AI is now part of our design system toolkit and design systems are part of our AI toolkit.
  • But the rapid onset of AI also raises higher level questions about what designers and developers should be doing in the future? We're more than rectangle creators. We think and feel which differentiates us from just production level tasks. Use your brains, your intuition, and whole self to solve real problems.

Smashing Conf: How to Use AI to Build Accessible Products

LukeW - Mon, 10/07/2024 - 2:00pm

In her How to Use AI to Build Accessible Products presentation at Smashing Conf New York, Carie Fisher discussed using AI coding tools to test and suggest fixes for accessibility issues in Web pages. Here's my notes on her talk.

  • AI is everywhere. You can use it to write content, code, create images, and more. It impacts how everyone will work.
  • But ultimately, AI is just a tool but it might not always be the right one. We need to find the tasks where it has the potential to add value.
  • Over 1 billion people on the planet identify as having a disability. Accessible code allows them to access digital experiences and helps companies be complaint with emerging laws requiring accessible Web pages and apps. Businesses also get SEO, brand, and more benefits from accessible code.
  • AI tools like Github Copilot can find accessibility issues in seconds consistently, especially compared to the manual checks currently being done by humans. AI can also spot patterns across a codebase and suggest solutions.
  • Existing AI coding tools like Github Copilot are already better than Linters for finding accessibility issues.
  • AI can suggest and implement code fixes for accessibility issues. It can also be added to CI/CD pipelines to check for accessibility issues at the point of each commit. AI can also serve as an accessibility mentor for developers by providing real-time suggestions.
  • More complex accessibility issues especially those that need user context may go unfound when just using AI. Sometimes AI output can be incomplete or hallucinate solutions that are not correct. As a result, we can't over rely on just AI to solve all accessibility problems. We still need human review today.
  • To improve AI accessibility, provide expanded prompts that reference or include specifications. Code reviews can double check accessibility suggestions from AI-based systems. Regularly test and refine your AI-based solutions to improve outcomes.
  • Combing AI and human processes and values can help build a culture of accessibility.

Searching for a New CSS Logo

Css Tricks - Mon, 10/07/2024 - 6:49am

There is an amazing community effort happening in search of a new logo for CSS. I was a bit skeptical at first, as I never really considered CSS a “brand.” Why does it need a logo? For starters, the current logo seems… a bit dated.

Displayed quite prominently is the number 3. As in CSS version 3, or simply CSS3. Depending on your IDE’s selected icon pack of choice, CSS file icons are often only the number 3.

To give an incredibly glossed-over history of CSS3:

  • Earliest draft specification was in 1999!
  • Adoption began in 2011, when it was published as the W3C Recommendation.
  • It’s been used ever since? That can’t be right…

CSS is certainly not stuck in 2011. Take a look at all the features added to CSS in the past five years (warning, scrolling animation ahead):

CodePen Embed Fallback

(Courtesy of Alex Riviere)

Seems like this stems mainly from the discontinuation of version numbering for CSS. These days, we mostly reference newer CSS features by their individual specification level, such as Selectors Level 4 being the current Selectors specification, for example.

A far more general observation on the “progress” of CSS could be taking a look at features being implemented — things like Caniuse and Baseline are great for seeing when certain browsers implemented certain features. Similarly, the Interop Project is a group consisting of browsers figuring out what to implement next.

There are ongoing discussions about the “eras” of CSS, though, and how those may be a way of framing the way we refer to CSS features.

Chris posted about CSS4 here on CSS-Tricks (five years ago!), discussing how successful CSS3 was from a marketing perspective. Jen Simmons also started a discussion back in 2020 on the CSS Working Group’s GitHub about defining CSS4. Knowing that, are you at least somewhat surprised that we have blown right by CSS4 and are technically using CSS5?

The CSS-Next Community Group is leading the charge here, something that member Brecht de Ruyte introduced earlier this year at Smashing Magazine. The purpose of this group is to, well, determine what’s next for CSS! The group defines the CSS versions as:

  • CSS3 (~2009-2012): Level 3 CSS specs as defined by the CSSWG
  • CSS4 (~2013-2018): Essential features that were not part of CSS3, but are already a fundamental part of CSS.
  • CSS5 (~2019-2024): Newer features whose adoption is steadily growing.
  • CSS6 (~2025+): Early-stage features that are planned for future CSS.

Check out this slide deck from November 2023 detailing the need for defining stronger versioning. Their goals are clear in my opinion:

  1. Help developers learn CSS.
  2. Help educators teach CSS.
  3. Help employers define modern web skil…
  4. Help the community understand the progression of CSS capabilities over time.

Circling back around to the logo, I have to agree: Yes, it’s time for a change.

Back in August, Adam Argyle opened an issue on the CSS-Next project on GitHub to drum up ideas. The thread is active and ongoing, though appears to be honing in on a release candidate. Let’s take a look at some proposals!

Nils Binder, from 9elements, proposed this lovely design, riffing on the “cascade.” Note the river-like “S” shape flowing through the design.

Chris Kirk-Nielson pitched a neat interactive logo concept he put together a while back. The suggestion plays into the “CSS is Awesome” meme, where the content overflows the wrapper. While playful and recognizable, Nils raised an excellent point:

Regarding the reference to the ‘CSS IS AWESOME’ meme, I initially chuckled, of course. However, at the same time, the meme also represents CSS as something quirky, unpredictable, and full of bugs. I’m not sure if that’s the exact message that needs to be repeated in the logo. It feels like it reinforces the recurring ‘CSS is broken’ mantra. To exaggerate: CSS is subordinate to JS and somehow broken.

Wow, is this the end of an era for the familiar meme? 

It’s looking that way, as the current candidate builds off of Javi Aguilar’s proposal. Javi’s design is being iterated upon by the group, it’s shaping up and looks great hanging with friends:

Javi describes the design considerations in the thread. Personally, I’m a fan of the color choice, and the softer shape differentiates it from the more rigid JavaScript and Typescript logos.

As mentioned, the discussion is ongoing and the design is actively being worked on. You can check out the latest versions in Adam’s CodePen demo:

Or if checking out design files is more your speed, take a look in Figma.

CodePen Embed Fallback

I think the thing that impresses me most about community initiatives like this is the collaboration involved. If you have opinions on the design of the logo, feel free to chime in on the discussion thread!

Once the versions are defined and the logo finalized, the only thing left to decide on will be a mascot for CSS. A chameleon? A peacock? I’m sure the community will choose wisely.

Searching for a New CSS Logo originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

CSS Anchor Positioning Guide

Css Tricks - Wed, 10/02/2024 - 5:26am

Not long ago, if we wanted a tooltip or popover positioned on top of another element, we would have to set our tooltip’s position to something other than static and use its inset/transform properties to place it exactly where we want. This works, but the element’s position is susceptible to user scrolls, zooming, or animations since the tooltip could overflow off of the screen or wind up in an awkward position. The only way to solve this was using JavaScript to check whenever the tooltip goes out of bounds so we can correct it… again in JavaScript.

CSS Anchor Positioning gives us a simple interface to attach elements next to others just by saying which sides to connect — directly in CSS. It also lets us set a fallback position so that we can avoid the overflow issues we just described. For example, we might set a tooltip element above its anchor but allow it to fold underneath the anchor when it runs out of room to show it above.

Anchor positioning is different from a lot of other features as far as how quickly it’s gained browser support: its first draft was published on June 2023 and, just a year later, it was released on Chrome 125. To put it into perspective, the first draft specification for CSS variables was published in 2012, but it took four years for them to gain wide browser support.

So, let’s dig in and learn about things like attaching target elements to anchor elements and positioning and sizing them.

Quick reference /* Define an anchor element */ .anchor { anchor-name: --my-anchor; } /* Anchor a target element */ .target { position: absolute; position-anchor: --my-anchor; } /* Position a target element */ .target { position-area: start end; } Table of contents
  1. Basics and terminology
  2. Attaching targets to anchors
  3. Positioning targets
  4. Setting fallback positions
  5. Custom position and size fallbacks
  6. Multiple anchors
  7. Accessibility
  8. Browser support
  9. Spec changes
  10. Known bugs
  11. Almanac references
  12. Further reading
Basics and terminology

At its most basic, CSS Anchor Positioning introduces a completely new way of placing elements on the page relative to one another. To make our lives easier, we’re going to use specific names to clarify which element is connecting to which:

  • Anchor: This is the element used as a reference for positioning other elements, hence the anchor name.
  • Target: This is an absolutely positioned element placed relative to one or more anchors. The target is the name we will use from now on, but you will often find it as just an “absolutely positioned element” in the spec.

For the following code examples and demos, you can think of these as just two <div> elements next to one another.

<div class="anchor">anchor</div> <div class="target">target</div>

CSS Anchor Positioning is all about elements with absolute positioning (i.e., position: absolute), so there are also some concepts we have to review before diving in.

  • Containing Block: This is the box that contains the elements. For an absolute element, the containing block is the viewport the closest ancestor with a position other than static or certain values in properties like contain or filter.
  • Inset-Modified Containing Block (IMCB): For an absolute element, inset properties (top, right, bottom, left, etc.) reduce the size of the containing block into which it is sized and positioned, resulting in a new box called the inset-modified containing block, or IMCB for short. This is a vital concept to know since properties we’re covering in this guide — like position-area and position-try-order — rely on this concept.
Attaching targets to anchors

We’ll first look at the two properties that establish anchor positioning. The first, anchor-name, establishes the anchor element, while the second, position-anchor, attaches a target element to the anchor element.

anchor-name

A normal element isn’t an anchor by default — we have to explicitly make an element an anchor. The most common way is by giving it a name, which we can do with the anchor-name property.

anchor-name: none | <dashed-ident>#

The name must be a <dashed-ident>, that is, a custom name prefixed with two dashes (--), like --my-anchor or --MyAnchor.

.anchor { anchor-name: --my-anchor; }

This gives us an anchor element. All it needs is something anchored to it. That’s what we call the “target” element which is set with the position-anchor property.

position-anchor

The target element is an element with an absolute position linked to an anchor element matching what’s declared on the anchor-name property. This attaches the target element to the anchor element.

position-anchor: auto | <anchor-element>

It takes a valid <anchor-element>. So, if we establish another element as the “anchor” we can set the target with the position-anchor property:

.target { position: absolute; position-anchor: --my-anchor; }

Normally, if a valid anchor element isn’t found, then other anchor properties and functions will be ignored.

Positioning targets

Now that we know how to establish an anchor-target relationship, we can work on positioning the target element in relation to the anchor element. The following two properties are used to set which side of the anchor element the target is positioned on (position-area) and conditions for hiding the target element when it runs out of room (position-visibility).

position-area

The next step is positioning our target relative to its anchor. The easiest way is to use the position-area property, which creates an imaginary 3×3 grid around the anchor element and lets us place the target in one or more regions of the grid.

position-area: auto | <position-area>

It works by setting the row and column of the grid using logical values like start and end (dependent on the writing mode); physical values like top, left, right, bottom and the center shared value, then it will shrink the target’s IMCB into the region of the grid we chose.

.target { position-area: top right; /* or */ position-area: start end; }

Logical values refer to the containing block’s writing mode, but if we want to position our target relative to its writing mode we would prefix it with the self value.

.target { position-area: self-start self-end; }

There is also the center value that can be used in every axis.

.target { position-area: center right; /* or */ position-area: start center; }

To place a target across two adjacent grid regions, we can use the prefix span- on any value (that isn’t center) a row or column at a time.

.target { position-area: span-top left; /* or */ position-area: span-start start; }

Finally, we can span a target across three adjacent grid regions using the span-all value.

.target { position-area: bottom span-all; /* or */ position-area: end span-all; }

You may have noticed that the position-area property doesn’t have a strict order for physical values; writing position-area: top left is the same as position-area: left top, but the order is important for logical value since position-area: start end is completely opposite to position-area: end start.

We can make logical values interchangeable by prefixing them with the desired axis using y-, x-, inline- or block-.

.target { position-area: inline-end block-start; /* or */ position-area: y-start x-end; } CodePen Embed Fallback CodePen Embed Fallback position-visibility

It provides certain conditions to hide the target from the viewport.

position-visibility: always | anchors-visible | no-overflow
  • always: The target is always displayed without regard for its anchors or its overflowing status.
  • no-overflow: If even after applying the position fallbacks, the target element is still overflowing its containing block, then it is strongly hidden.
  • anchors-visible: If the anchor (not the target) has completely overflowed its containing block or is completely covered by other elements, then the target is strongly hidden.
position-visibility: always | anchors-visible | no-overflow CodePen Embed Fallback Setting fallback positions

Once the target element is positioned against its anchor, we can give the target additional instructions that tell it what to do if it runs out of space. We’ve already looked at the position-visibility property as one way of doing that — we simply tell the element to hide. The following two properties, however, give us more control to re-position the target by trying other sides of the anchor (position-try-fallbacks) and the order in which it attempts to re-position itself (position-try-order).

The two properties can be declared together with the position-try shorthand property — we’ll touch on that after we look at the two constituent properties.

position-try-fallbacks

This property accepts a list of comma-separated position fallbacks that are tried whenever the target overflows out of space in its containing block. The property attempts to reposition itself using each fallback value until it finds a fit or runs out of options.

position-try-fallbacks: none | [ [<dashed-ident> || <try-tactic>] | <'inset-area'> ]#
  • none: Leaves the target’s position options list empty.
  • <dashed-ident>: Adds to the options list a custom @position-try fallback with the given name. If there isn’t a matching @position-try, the value is ignored.
  • <try-tactic>: Creates an option list by flipping the target’s current position on one of three axes, each defined by a distinct keyword. They can also be combined to add up their effects.
    • The flip-block keyword swaps the values in the block axis.
    • The flip-inline keyword swaps the values in the inline axis.
    • The flip-start keyword swaps the values diagonally.
  • <dashed-ident> || <try-tactic>: Combines a custom @try-option and a <try-tactic> to create a single-position fallback. The <try-tactic> keywords can also be combined to sum up their effects.
  • <"position-area"> Uses the position-area syntax to move the anchor to a new position.
.target { position-try-fallbacks: --my-custom-position, --my-custom-position flip-inline, bottom left; } position-try-order

This property chooses a new position from the fallback values defined in the position-try-fallbacks property based on which position gives the target the most space. The rest of the options are reordered with the largest available space coming first.

position-try-order: normal | most-width | most-height | most-block-size | most-inline-size

What exactly does “more space” mean? For each position fallback, it finds the IMCB size for the target. Then it chooses the value that gives the IMCB the widest or tallest size, depending on which option is selected:

  • most-width
  • most-height
  • most-block-size
  • most-inline-size
.target { position-try-fallbacks: --custom-position, flip-start; position-try-order: most-width; } position-try

This is a shorthand property that combines the position-try-fallbacks and position-try-order properties into a single declaration. It accepts first the order and then the list of possible position fallbacks.

position-try: < "position-try-order" >? < "position-try-fallbacks" >;

So, we can combine both properties into a single style rule:

.target { position-try: most-width --my-custom-position, flip-inline, bottom left; } Custom position and size fallbacks @position-try

This at-rule defines a custom position fallback for the position-try-fallbacks property.

@position-try <dashed-ident> { <declaration-list> }

It takes various properties for changing a target element’s position and size and grouping them as a new position fallback for the element to try.

Imagine a scenario where you’ve established an anchor-target relationship. You want to position the target element against the anchor’s top-right edge, which is easy enough using the position-area property we saw earlier:

.target { position: absolute; position-area: top right; width: 100px; }

See how the .target is sized at 100px? Maybe it runs out of room on some screens and is no longer able to be displayed at anchor’s the top-right edge. We can supply the .target with the fallbacks we looked at earlier so that it attempts to re-position itself on an edge with more space:

.target { position: absolute; position-area: top right; position-try-fallbacks: top left; position-try-order: most-width; width: 100px; }

And since we’re being good CSSer’s who strive for clean code, we may as well combine those two properties with the position-try shorthand property:

.target { position: absolute; position-area: top right; position-try: most-width, flip-inline, bottom left; width: 100px; }

So far, so good. We have an anchored target element that starts at the top-right corner of the anchor at 100px. If it runs out of space there, it will look at the position-try property and decide whether to reposition the target to the anchor’s top-left corner (declared as flip-inline) or the anchor’s bottom-left corner — whichever offers the most width.

But what if we want to simulataneously re-size the target element when it is re-positioned? Maybe the target is simply too dang big to display at 100px at either fallback position and we need it to be 50px instead. We can use the @position-try to do exactly that:

@position-try --my-custom-position { position-area: top left; width: 50px; }

With that done, we now have a custom property called --my-custom-position that we can use on the position-try shorthand property. In this case, @position-try can replace the flip-inline value since it is the equivalent of top left:

@position-try --my-custom-position { position-area: top left; width: 50px; } .target { position: absolute; position-area: top right; position-try: most-width, --my-custom-position, bottom left; width: 100px; }

This way, the .target element’s width is re-sized from 100px to 50px when it attempts to re-position itself to the anchor’s top-right edge. That’s a nice bit of flexibility that gives us a better chance to make things fit together in any layout.

Anchor functions anchor()

You might think of the CSS anchor() function as a shortcut for attaching a target element to an anchor element — specify the anchor, the side we want to attach to, and how large we want the target to be in one fell swoop. But, as we’ll see, the function also opens up the possibility of attaching one target element to multiple anchor elements.

This is the function’s formal syntax, which takes up to three arguments:

anchor( <anchor-element>? && <anchor-side>, <length-percentage>? )

So, we’re identifying an anchor element, saying which side we want the target to be positioned on, and how big we want it to be. It’s worth noting that anchor() can only be declared on inset-related properties (e.g. top, left, inset-block-end, etc.)

.target { top: anchor(--my-anchor bottom); left: anchor(--my-anchor end, 50%); }

Let’s break down the function’s arguments.

<anchor-element>

This argument specifies which anchor element we want to attach the target to. We can supply it with either the anchor’s name (see “Attaching targets to anchors”).

We also have the choice of not supplying an anchor at all. In that case, the target element uses an implicit anchor element defined in position-anchor. If there isn’t an implicit anchor, the function resolves to its fallback. Otherwise, it is invalid and ignored.

<anchor-side>

This argument sets which side of the anchor we want to position the target element to, e.g. the anchor’s top, left, bottom, right, etc.

But we have more options than that, including logical side keywords (inside, outside), logical direction arguments relative to the user’s writing mode (start, end, self-start, self-end) and, of course, center.

  • <anchor-side>: Resolves to the <length> of the corresponding side of the anchor element. It has physical arguments (top, left, bottom right), logical side arguments (inside, outside), logical direction arguments relative to the user’s writing mode (start, end, self-start, self-end) and the center argument.
  • <percentage>: Refers to the position between the start (0%) and end (100%). Values below 0% and above 100% are allowed.
<length-percentage>

This argument is totally optional, so you can leave it out if you’d like. Otherwise, use it as a way of re-sizing the target elemenrt whenever it doesn’t have a valid anchor or position. It positions the target to a fixed <length> or <percentage> relative to its containing block.

Let’s look at examples using different types of arguments because they all do something a little different.

Using physical arguments

Physical arguments (top, right, bottom, left) can be used to position the target regardless of the user’s writing mode. For example, we can position the right and bottom inset properties of the target at the anchor(top) and anchor(left) sides of the anchor, effectively positioning the target at the anchor’s top-left corner:

.target { bottom: anchor(top); right: anchor(left); }

Using logical side keywords

Logical side arguments (i.e., inside, outside), are dependent on the inset property they are in. The inside argument will choose the same side as its inset property, while the outside argument will choose the opposite. For example:

.target { left: anchor(outside); /* is the same as */ left: anchor(right); top: anchor(inside); /* is the same as */ top: anchor(top); }

Using logical directions

Logical direction arguments are dependent on two factors:

  1. The user’s writing mode: they can follow the writing mode of the containing block (start, end) or the target’s own writing mode (self-start, self-end).
  2. The inset property they are used in: they will choose the same axis of their inset property.

So for example, using physical inset properties in a left-to-right horizontal writing would look like this:

.target { left: anchor(start); /* is the same as */ left: anchor(left); top: anchor(end); /* is the same as */ top: anchor(bottom); }

In a right-to-left writing mode, we’d do this:

.target { left: anchor(start); /* is the same as */ left: anchor(right); top: anchor(end); /* is the same as */ top: anchor(bottom); }

That can quickly get confusing, so we should also use logical arguments with logical inset properties so the writing mode is respected in the first place:

.target { inset-inline-start: anchor(end); inset-block-start: anchor(end); }

Using percentage values

Percentages can be used to position the target from any point between the start (0%) and end (100% ) sides. Since percentages are relative to the user writing mode, is preferable to use them with logical inset properties.

.target { inset-inline-start: anchor(100%); /* is the same as */ inset-inline-start: anchor(end); inset-block-end: anchor(0%); /* is the same as */ inset-block-end: anchor(start); }

Values smaller than 0% and bigger than 100% are accepted, so -100% will move the target towards the start and 200% towards the end.

.target { inset-inline-start: anchor(200%); inset-block-end: anchor(-100%); }

Using the center keyword

The center argument is equivalent to 50%. You could say that it’s “immune” to direction, so there is no problem if we use it with physical or logical inset properties.

.target { position: absolute; position-anchor: --my-anchor; left: anchor(center); bottom: anchor(top); }

anchor-size()

The anchor-size() function is unique in that it sizes the target element relative to the size of the anchor element. This can be super useful for ensuring a target scales in size with its anchor, particularly in responsive designs where elements tend to get shifted, re-sized, or obscured from overflowing a container.

The function takes an anchor’s side and resolves to its <length>, essentially returning the anchor’s width, height, inline-size or block-size.

anchor-size( [ <anchor-element> || <anchor-size> ]? , <length-percentage>? )

Here are the arguments that can be used in the anchor-size() function:

  • <anchor-size>: Refers to the side of the anchor element.
  • <length-percentage>: This optional argument can be used as a fallback whenever the target doesn’t have a valid anchor or size. It returns a fixed <length> or <percentage> relative to its containing block.

And we can declare the function on the target element’s width and height properties to size it with the anchor — or both at the same time!

.target { width: anchor-size(width, 20%); /* uses default anchor */` height: anchor-size(--other-anchor inline-size, 100px); } Multiple anchors

We learned about the anchor() function in the last section. One of the function’s quirks is that we can only declare it on inset-based properties, and all of the examples we saw show that. That might sound like a constraint of working with the function, but it’s actually what gives anchor() a superpower that anchor positioning properties don’t: we can declare it on more than one inset-based property at a time. As a result, we can set the function multiple anchors on the same target element!

Here’s one of the first examples of the anchor() function we looked at in the last section:

.target { top: anchor(--my-anchor bottom); left: anchor(--my-anchor end, 50%); }

We’re declaring the same anchor element named --my-anchor on both the top and left inset properties. That doesn’t have to be the case. Instead, we can attach the target element to multiple anchor elements.

.anchor-1 { anchor-name: --anchor-1; } .anchor-2 { anchor-name: --anchor-2; } .anchor-3 { anchor-name: --anchor-3; } .anchor-4 { anchor-name: --anchor-4; } .target { position: absolute; inset-block-start: anchor(--anchor-1); inset-inline-end: anchor(--anchor-2); inset-block-end: anchor(--anchor-3); inset-inline-start: anchor(--anchor-4); }

Or, perhaps more succintly:

.anchor-1 { anchor-name: --anchor-1; } .anchor-2 { anchor-name: --anchor-2; } .anchor-3 { anchor-name: --anchor-3; } .anchor-4 { anchor-name: --anchor-4; } .target { position: absolute; inset: anchor(--anchor-1) anchor(--anchor-2) anchor(--anchor-3) anchor(--anchor-4); }

The following demo shows a target element attached to two <textarea> elements that are registered anchors. A <textarea> allows you to click and drag it to change its dimensions. The two of them are absolutely positioned in opposite corners of the page. If we attach the target to each anchor, we can create an effect where resizing the anchors stretches the target all over the place almost like a tug-o-war between the two anchors.

CodePen Embed Fallback

The demo is only supported in Chrome at the time we’re writing this guide, so let’s drop in a video so you can see how it works.

Accessibility

The most straightforward use case for anchor positioning is for making tooltips, info boxes, and popovers, but it can also be used for decorative stuff. That means anchor positioning doesn’t have to establish a semantic relationship between the anchor and target elements. You can probably spot the issue right away: non-visual devices, like screen readers, are left in the dark about how to interpret two seemingly unrelated elements.

As an example, let’s say we have an element called .tooltip that we’ve set up as a target element anchored to another element called .anchor.

<div class="anchor">anchor</div> <div class="toolip">toolip</div> .anchor { anchor-name: --my-anchor; } .toolip { position: absolute; position-anchor: --my-anchor; position-area: top; }

We need to set up a connection between the two elements in the DOM so that they share a context that assistive technologies can interpret and understand. The general rule of thumb for using ARIA attributes to describe elements is generally: don’t do it. Or at least avoid doing it unless you have no other semantic way of doing it.

This is one of those cases where it makes sense to reach for ARIA atributes. Before we do anything else, a screen reader currently sees the two elements next to one another without any remarking relationship. That’s a bummer for accessibility, but we can easily fix it using the corresponding ARIA attribute:

<div class="anchor" aria-describedby="tooltipInfo">anchor</div> <div class="toolip" role="tooltip" id="tooltipInfo">toolip</div>

And now they are both visually and semantically linked together! If you’re new to ARIA attributes, you ought to check out Adam Silver’s “Why, How, and When to Use Semantic HTML and ARIA” for a great introduction.

Browser support

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

DesktopChromeFirefoxIEEdgeSafari125NoNo125NoMobile / TabletAndroid ChromeAndroid FirefoxAndroidiOS Safari129No129No Spec changes

CSS Anchor Positioning has undergone several changes since it was introduced as an Editor’s Draft. The Chrome browser team was quick to hop on board and implement anchor positioning even though the feature was still being defined. That’s caused confusion because Chromium-based browsers implemented some pieces of anchor positioning while the specification was being actively edited.

We are going to outline specific cases for you where browsers had to update their implementations in response to spec changes. It’s a bit confusing, but as of Chrome 129+, this is the stuff that was shipped but changed:

position-area

The inset-area property was renamed to position-area (#10209), but it will be supported until Chrome 131.

.target { /* from */ inset-area: top right; /* to */ position-area: top right; } position-try-fallbacks

The position-try-options was renamed to position-try-fallbacks (#10395).

.target { /* from */ position-try-options: flip-block, --smaller-target; /* to */ position-try-fallbacks: flip-block, --smaller-target; } inset-area()

The inset-area() wrapper function doesn’t exist anymore for the position-try-fallbacks (#10320), you can just write the values without the wrapper:

.target { /* from */ position-try-options: inset-area(top left); /* to */ position-try-fallbacks: top left; } anchor(center)

In the beginning, if we wanted to center a target from the center, we would have to write this convoluted syntax:

.target { --center: anchor(--x 50%); --half-distance: min(abs(0% - var(--center)), abs(100% - var(--center))); left: calc(var(--center) - var(--half-distance)); right: calc(var(--center) - var(--half-distance)); }

The CWSSG working group resolved (#8979) to add the anchor(center) argument to prevent us from having to do all that mental juggling:

.target { left: anchor(center); } Known bugs

Yes, there are some bugs with CSS Anchor Positioning, at least at the time this guide is being written. For example, the specification says that if an element doesn’t have a default anchor element, then the position-area does nothing. This is a known issue (#10500), but it’s still possible to replicate.

So, the following code…

.container { position: relative; } .element { position: absolute; position-area: center; margin: auto; }

…will center the .element inside its container, at least in Chrome:

CodePen Embed Fallback

Credit to Afif13 for that great demo!

Another example involves the position-visibility property. If your anchor element is out of sight or off-screen, you typically want the target element to be hidden as well. The specification says that property’s the default value is anchors-visible, but browsers default to always instead.

The current implemenation in Chrome isn’t reflecting the spec; it indeed is using always as the initial value. But the spec is intentional: if your anchor is off-screen or otherwise scrolled off, you usually want it to hide. (#10425)

Almanac references Anchor position properties Almanac on Sep 17, 2024 anchor-name .anchor { anchor-name: --my-anchor; } Geoff Graham Almanac on Sep 12, 2024 position-anchor .target { position-anchor: --my-anchor; } Juan Diego Rodríguez Almanac on Sep 8, 2024 position-area .target { position-area: bottom end; } Juan Diego Rodríguez Almanac on Sep 14, 2024 position-try-fallbacks .target { position-try-fallbacks: flip-inline, bottom left; } Juan Diego Rodríguez Almanac on Sep 8, 2024 position-try-order .element { position-try-order: most-width; } Juan Diego Rodríguez Almanac on Sep 8, 2024 position-visibility .target { position-visibility: no-overflow; } Juan Diego Rodríguez Anchor position functions Almanac on Sep 14, 2024 anchor() .target { top: anchor(--my-anchor bottom); } Juan Diego Rodríguez Almanac on Sep 18, 2024 anchor-size() .target { width: anchor-size(width); } Juan Diego Rodríguez Anchor position at-rules Almanac on Sep 28, 2024 @position-try @position-try --my-position { position-area: top left; } Juan Diego Rodríguez Further reading

CSS Anchor Positioning Guide originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Ask Luke: Streaming Inline Images

LukeW - Mon, 09/30/2024 - 2:00pm

Since launching the Ask Luke feature on this site last year, we've added the ability for the system to respond to questions about product design by citing articles, videos, audio, and PDFs. Now we're introducing the ability to cite the thousands of images I've created over the years and reference them directly in answers.

Significant improvements in AI vision models have given us the ability to quickly and easily describe visual content. I recently outlined how we used this capability to index the content of PDF pages in more depth making individual PDF pages a much better source of content in the Ask Luke corpus.

We applied the same process and pipeline to the thousands of images I've created for articles and presentations over the years. Essentially, each image on my Website gets parsed by a vision model and we add the resulting text-based description to the set of content we can use to answer people's design questions. Here's an example of the kinds of descriptions we're creating. As you can see, the descriptions can get pretty detailed when needed.

If someone asks a question where an image is a key part of the answer, our replies not only return streaming text and citations but inline images as well. In this question asking about Amazon's design changes over the years, multiple images are included directly in the response.

Not only are images displayed where relevant, the answer refers to them and often refers to the contents of the image. In the same Amazon navigation example, the answer refers to the green and white color scheme of the image in addition to its contents.

Now that we've got citations and images steaming inline in Ask Luke responses, perhaps adding inline videos and audio files queued to relevant timestamps might be next? We're already integrating those in the conversational UI so why not... AI is a hell of a drug.

Further Reading

Additional articles about what I've tried and learned by rethinking the design and development of my Website using large-scale AI models.

Acknowledgments

Big thanks to Sidharth Lakshmanan and Sam Breed for the development help.

CSS Masonry & CSS Grid

Css Tricks - Mon, 09/30/2024 - 3:56am

An approach for creating masonry layouts in vanilla CSS is one of those “holy grail” aspirations. I actually tend to plop masonry and the classic “Holy Grail” layout in the same general era of web design. They’re different types of layouts, of course, but the Holy Grail was a done deal when we got CSS Grid.

That leaves masonry as perhaps the last standing layout from the CSS 3 era that is left without a baked-in solution. I might argue that masonry is no longer en vogue so to speak, but there clearly are use cases for packing items with varying sizes into columns based on available space. And masonry is still very much in the wild.

Steam is picking up on a formal solution. We even have a CSSWG draft specification for it. But notice how the draft breaks things out.

Grid-integrated syntax? Grid-independent syntax? We’ve done gone and multiplied CSS!

That’s the context for this batch of notes. There are two competing proposals for CSS masonry at the time of writing and many opinions are flying around advocating one or the other. I have personal thoughts on it, but that’s not important. I’ll be happy with whatever the consensus happens to be. Both proposals have merits and come with potential challenges — it’s a matter of what you prioritize which, in this case, I believe is a choice between leveraging existing CSS layout features and the ergonomics of a fresh new approach.

But let’s get to some notes from discussions that are already happening to help get a clearer picture of things!

What is masonry layout?

Think of it like erecting a wall of stones or bricks.

The sizes of the bricks and stones don’t matter — the column (or less commonly a row) is the boss of sizing things. Pack as many stones or bricks in the nearest column and then those adapt to the column’s width. Or more concisely, we’re laying out unevenly sized items in a column such that there aren’t uneven gaps between them.

Examples, please?

Here’s perhaps the most widely seen example in a CodePen, courtesy of Dave DeSandro, using his Masonry.js tool:

CodePen Embed Fallback

I use this example because, if I remember correctly, Masonry.js was what stoked the masonry trend in, like 2010 or something. Dave implemented it on Beyoncé’s website which certainly gave masonry a highly visible profile. Sometimes you might hear masonry called a “Pinterest-style” layout because, well, that’s been the site’s signature design — perhaps even its brand — since day one.

Here’s a faux example Jhey put together using flexbox:

CodePen Embed Fallback

Chris also rounded up a bunch of other workarounds in 2019 that get us somewhat there, under ideal conditions. But none of these are based on standardized approaches or features. I mean, columns and flexbox are specced but weren’t designed with masonry in mind. But with masonry having a long track record of being used, it most certainly deserves a place in the CSS specs.

There are two competing proposals

This isn’t exactly news. In fact, we can get earlier whiffs of this looking back to 2020. Rachel Andrew introduced the concept of making masonry a sub-feature of grid in a Smashing Magazine article.

Let’s fast-forward to 2022. We had an editor’s draft for CSS Masonry baked into the CSS Grid Layout Module 3 specification. Jenn Simmons motioned for the CSSWG to move it forward to be a first public working draft. Five days later, Chromium engineer Ian Kilpatrick raised two concerns about moving things forward as part of the CSS Grid Layout module, the first being related to sizing column tracks and grid’s layout algorithm:

Grid works by placing everything in the grid ahead of time, then sizing the rows/columns to fit the items. Masonry fundamentally doesn’t work this way as you need to size the rows/columns ahead of time – then place items within those rows/columns.

As a result the way the current specification re-uses the grid sizing logic leads to poor results when intrinsically sizing tracks, and if the grid is intrinsically-sized itself (e.g. if its within a grid/flex/table, etc).

Good point! Grid places grid items in advance ahead of sizing them to fit into the available space. Again, it’s the column’s size that bosses things around in masonry. It logically follows that we would need to declare masonry and configure the column track sizes in advance to place things according to space. The other concern concerns accessibility as far as visual and reading order.

That stopped Jenn’s motion for first public working draft status dead in its tracks in early 2023. If we fast-forward to July of this year, we get Ian’s points for an alternative path forward for masonry. That garnered support from all sorts of CSS heavyweights, including Rachel Andrew who authored the CSS Grid specification.

And, just a mere three weeks ago from today, fantasai shared a draft for an alternate proposal put together with Tab Atkins. This proposal, you’ll see, is specific to masonry as its own module.

And thus we have two competing proposals to solve masonry in CSS.

The case for merging masonry and grid

Rounding up comments from GitHub tickets and blog posts…

Flexbox is really designed for putting things into a line and distributing spare space. So that initial behaviour of putting all your things in a row is a great starting point for whatever you might want to do. It may be all you need to do. It’s not difficult as a teacher to then unpack how to add space inside or outside items, align them, or make it a column rather than a row. Step by step, from the defaults.

I want to be able to take the same approach with display: masonry.

[…]

We can’t do that as easily with grid, because of the pre-existing initial values. The good defaults for grid don’t work as well for masonry. Currently you’d need to:

  1. Add display: grid, to get a single column grid layout.
  2. Add grid-template-columns: <track-listing>, and at the moment there’s no way to auto-fill auto sized tracks so you’ll need to decide on how many. Using grid-template-columns: repeat(3, auto), for example.
  3. Add grid-template-rows: masonry.
  4. Want to define rows instead? Switch the masonry value to apply to  grid-template-columns and now define your rows. Once again, you have to explicitly define rows.
Rachel Andrew, Masonry and good defaults”

For what it’s worth, Rachel has been waving this flag since at least 2020. The ergonomics of display: masonry with default configurations that solve baseline functionality are clear and compelling. The default behavior oughta match the feature’s purpose and grid just ain’t a great set of default configurations to jump into a masonry layout. Rachel’s point is that teaching and learning grid to get to understand masonry behavior unnecessarily lumps two different formatting contexts into one, which is a certain path to confusion. I find it tough to refute this, as I also come at this from a teaching perspective. Seen this way, we might say that merging features is another lost entry point into front-end development.

In recent years, the two primary methods we’ve used to pull off masonry layouts are:

  • Flexbox for consistent row sizes. We adjust the flex-basis based on the item’s expected percentage of the total row width.
  • Grid for consistent column sizes. We set the row span based on the expected aspect ratio of the content, either server-side for imagery or client-side for dynamic content.

What I’ve personally observed is:

  • Neither feels more intuitive than the other as a starting point for masonry. So it feels a little itchy to single out Grid as a foundation.
  • While there is friction when teaching folks when to use a Flexbox versus a Grid, it’s a much bigger leap for contributors to wrap their heads around properties that significantly change behavior (such as flex-wrap or grid-auto-flow: dense).
Tyler Sticka, commenting on GitHub Issue #9041

It’s true! If I had to single out either flexbox or grid as the starting poit for masonry (and I doubt I would either way), I might lean flexbox purely for the default behavior of aligning flexible items in a column.

The syntax and semantics of the CSS that will drive masonry layout is a concern that is separate from the actual layout mechanics itself, which internally in implementation by user agents can still re-use parts of the existing mechanics for grids, including subgrids. For cases where masonry is nested inside grid, or grid inside masonry, the relationship between the two can be made explicit.

@jgotten, commenting on GitHub Issue #9041

Rachel again, this time speaking on behalf of the Chrome team:

There are two related reasons why we feel that masonry is better defined outside of grid layout—the potential of layout performance issues, and the fact that both masonry and grid have features that make sense in one layout method but not the other.

The case for keeping masonry separate from grid

One of the key benefits of integrating masonry into the grid layout (as in CASE 2) is the ability to leverage existing grid features, such as subgrids. Subgrids allow for cohesive designs among child elements within a grid, something highly desirable in many masonry layouts as well. Additionally, I believe that future enhancements to the grid layout will also be beneficial for masonry, making their integration even more valuable. By treating masonry as an extension of the grid layout, developers would be able to start using it immediately, without needing to learn a completely new system.

Kokomi, commenting on GitHub Issue #9041

It really would be a shame if keeping masonry separate from grid prevents masonry from being as powerful as it could be with access to grid’s feature set:

I think the arguments for a separate display: masonry focus too much on the potential simplicity at the expense of functionality. Excluding Grid’s powerful features would hinder developers who want or need more than basic layouts. Plus, introducing another display type could lead to confusion and fragmentation in the layout ecosystem.

Angel Ponce, commenting on GitHub Issue #9041

Rachel counters that, though.

I want express my strong support for adding masonry to display:grid. The fact that it gracefully degrades to a traditional grid is a huge benefit IMO. But also, masonry layout is already possible (with some constraints) in Grid layout today!

Naman Goel, Angel Ponce, commenting on GitHub Issue #9041

Chris mildly voiced interest in merging the two in 2020 before the debate got larger and more heated. Not exactly a ringing endorsement, but rather an acknowledgment that it could make sense:

I like the grid-template-rows: masonry; syntax because I think it clearly communicates: “You aren’t setting these rows. In fact, there aren’t even really rows at all anymore, we’ll take care of that.” Which I guess means there are no rows to inherit in subgrid, which also makes sense.

Where we at?

Collecting feedback. Rachel, Ian, and Tab published a joint call for folks like you and me to add our thoughts to the bag. That was eight days ago as of this writing. Not only is it a call to action, but it’s also an excellent overview of the two competing ideas and considerations for each one. You’ll want to add your feedback to GitHub Issue #9041.

CSS Masonry & CSS Grid originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Syndicate content
©2003 - Present Akamai Design & Development.