Web Standards

The New CSS Media Query Range Syntax

Css Tricks - Mon, 10/31/2022 - 3:05am

We rely on CSS Media Queries for selecting and styling elements based on a targeted condition. That condition can be all kinds of things but typically fall into two camps: (1) the type of media that’s being used, and (2) a specific feature of the browser, device, or even the user’s environment.

So, say we want to apply certain CSS styling to a printed document:

@media print { .element { /* Style away! */ } }

The fact that we can apply styles at a certain viewport width has made CSS Media Queries a core ingredient of responsive web design since Ethan Marcotte coined the term. If the browser’s viewport width is a certain size, then apply a set of style rules, which allows us to design elements that respond to the size of the browser.

/* When the viewport width is at least 30em... */ @media screen and (min-width: 30em) { .element { /* Style away! */ } }

Notice the and in there? That’s an operator that allows us to combine statements. In that example, we combined a condition that the media type is a screen and that it’s min-width feature is set to 30em (or above). We can do the same thing to target a range of viewport sizes:

/* When the viewport width is between 30em - 80em */ @media screen and (min-width: 30em) and (max-width: 80em) { .element { /* Style away! */ } }

Now those styles apply to an explicit range of viewport widths rather than a single width!

But the Media Queries Level 4 specification has introduced a new syntax for targeting a range of viewport widths using common mathematical comparison operators — things like <, >, and = — that make more sense syntactically while writing less code.

Let’s dig into how that works.

New comparison operators

That last example is a good illustration of how we’ve sort of “faked” ranges by combining conditions using the and operator. The big change in the Media Queries Level 4 specification is that we have new operators that compare values rather than combining them:

  • < evaluates if a value is less than another value
  • > evaluates if a value is greater than another value
  • = evaluates if a value is equal to another value
  • <= evaluates if a value is less than or equal to another value
  • >= evaluates if a value is greater than or equal to another value

Here’s how we might’ve written a media query that applies styles if the browser is 600px wide or greater:

@media (min-width: 600px) { .element { /* Style away! */ } }

Here’s how it looks to write the same thing using a comparison operator:

@media (width >= 600px) { .element { /* Style away! */ } } Targeting a range of viewport widths

Often when we write CSS Media Queries, we’re creating what’s called a breakpoint — a condition where the design “breaks” and a set of styles are applied to fix it. A design can have a bunch of breakpoints! And they’re usually based on the viewport being between two widths: where the breakpoint starts and where the breakpoint ends.

Here’s how we’ve done that using the and operator to combine the two breakpoint values:

/* When the browser is between 400px - 1000px */ @media (min-width: 400px) and (max-width: 1000px) { /* etc. */ }

You start to get a good sense of how much shorter and easier it is to write a media query when we ditch the Boolean and operator in favor of the new range comparison syntax:

@media (400px <= width <= 1000px) { /* etc. */ }

Much easier, right? And it’s clear exactly what this media query is doing.

Browser support

This improved media query syntax is still in its early days at the time of this writing and not as widely supported at the moment as the approach that combines min-width and max-width. We’re getting close, though! Safari is the only major holdout at this point, but there is an open ticket for it that you can follow.

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

DesktopChromeFirefoxIEEdgeSafari10463No104NoMobile / TabletAndroid ChromeAndroid FirefoxAndroidiOS Safari107106107No Let’s look at an example

Here’s a layout for that’s nicely suited for larger screens, like a desktop:

This layout has base styles that are common to all breakpoints. But as the screen gets narrower, we start to apply styles that are conditionally applied at different smaller breakpoints that are ideally suited for tablets all the way down to mobile phones:

To see what’s happening, here’s a how the layout responds between the two smaller breakpoints. The hidden nav list getting displayed as well as title in the main gets increased in font-size.

That change is triggered when the viewport’s changes go from matching one media’s conditions to another:

/* Base styles (any screen size) */ header { display: flex; justify-content: center; } header ul { display: none; } .title p { font-size: 3.75rem; } /* When the media type is a screen with a width greater or equal to 768px */ @media screen and (width >= 768px) { header { justify-content: space-between; } header ul { display: flex; justify-content: space-between; gap: 3rem; } .title p { font-size: 5.75rem; } }

We’ve combined a few of the concepts we’ve covered! We’re targeting devices with a screen media type, evaluating whether the viewport width is greater than or equal to a specific value using the new media feature range syntax, and combining the two conditions with the and operator.

OK, so that’s great for mobile devices below 768px and for other devices equal to or greater than 768px. But what about that desktop layout… how do we get there?

As far as the layout goes:

  • The main element becomes a 12-column grid.
  • A button is displayed on the image.
  • The size of the .title element’s font increases and overlaps the image.

Assuming we’ve done our homework and determined exactly where those changes should take place, we can apply those styles when the viewport matches the width condition for that breakpoint. We’re going to say that breakpoint is at 1000px:

/* When the media type is a screen with a width greater or equal to 1000px */ @media screen and (width >= 1000px) { /* Becomes a 12-column grid */ main { display: grid; grid-template-columns: repeat(12, 1fr); grid-template-rows: auto 250px; } /* Places the .title on the grid */ .title { grid-row: 1; } /* Bumps up the font-size */ .title p { font-size: 7.75rem; } /* Places .images on the grid */ .images { grid-row: 1 / span 2; align-self: end; position: relative; } /* Displays the button */ .images .button { display: block; position: absolute; inset-block-end: 5rem; inset-inline-end: -1rem; } }

Have a play with it:

CodePen Embed Fallback Why the new syntax is easier to understand

The bottom line: it’s easier to distinguish a comparison operator (e.g. width >= 320px) than it is to tell the difference between min-width and max-width using the and operator. By removing the nuance between min- and max-, we have one single width parameter to work with and the operators tell us the rest.

Beyond the visual differences of those syntaxes, they are also doing slightly different things. Using min- and max- is equivalent to using mathematical comparison operators:

  • max-width is equivalent to the <= operator (e.g. (max-width: 320px) is the same as (width <= 320px)).
  • min-width is equivalent to the >= operator (e.g. (min-width: 320px) is the same as (width >= 320px)).

Notice that neither is the equivalent of the > or < operators.

Let’s pull an example straight from the Media Queries Level 4 specification where we define different styles based on a breakpoint at 320px in the viewport width using min-width and max-width:

@media (max-width: 320px) { /* styles for viewports <= 320px */ } @media (min-width: 320px) { /* styles for viewports >= 320px */ }

Both media queries match a condition when the viewport width is equal to 320px. That’s not exactly what we want. We want either one of those conditions rather than both at the same time. To avoid that implicit changes, we might add a pixel to the query based on min-width:

@media (max-width: 320px){ /* styles for viewports <= 320px */ } @media (min-width: 321px){ /* styles for viewports >= 321px */ }

While this ensures that the two sets of styles don’t apply simultaneously when the viewport width is 320px, any viewport width that fall between 320px and 321px will result in a super small zone where none of the styles in either query are applied — a weird “flash of unstyled content” situation.

One solution is to increase the second comparison scale value (numbers after the decimal point) to 320.01px:

@media (max-width: 320px) { /* styles for viewports <= 320px */ } @media (min-width: 320.01px) { /* styles for viewports >= 320.01px */ }

But that’s getting silly and overly complicated. That’s why the new media feature range syntax is a more appropriate approach:

@media (width <= 320px) { /* styles for viewports <= 320px */ } @media (width > 320px) { /* styles for viewports > 320px */ } Wrapping up

Phew, we covered a lot of ground on the new syntax for targeting viewport width ranges in CSS Media Queries. Now that the Media Queries Level 4 specification has introduced the syntax and it’s been adopted in Firefox and Chromium browsers, we’re getting close to being able to use the new comparison operators and combining them with other range media features besides width, like height and aspect-ratio

And that’s just one of the newer features that the Level 4 specification introduced, alongside a bunch of queries we can make based on user preferences. It doesn’t end there! Check out the Complete Guide to CSS Media Queries for a sneak peek of what might be included in Media Queries Level 5.

The New CSS Media Query Range Syntax originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Fancy Image Decorations: Outlines and Complex Animations

Css Tricks - Fri, 10/28/2022 - 2:45am

We’ve spent the last two articles in this three-part series playing with gradients to make really neat image decorations using nothing but the <img> element. In this third and final piece, we are going to explore more techniques using the CSS outline property. That might sound odd because we generally use outline to draw a simple line around an element — sorta like border but it can only draw all four sides at once and is not part of the Box Model.

We can do more with it, though, and that’s what I want to experiment with in this article.

Fancy Image Decorations series

Let’s start with our first example — an overlay that disappears on hover with a cool animation:

CodePen Embed Fallback

We could accomplish this by adding an extra element over the image, but that’s what we’re challenging ourselves not to do in this series. Instead, we can reach for the CSS outline property and leverage that it can have a negative offset and is able to overlap its element.

img { --s: 250px; /* the size of the image */ --b: 8px; /* the border thickness*/ --g: 14px; /* the gap */ --c: #4ECDC4; width: var(--s); aspect-ratio: 1; outline: calc(var(--s) / 2) solid #0009; outline-offset: calc(var(--s) / -2); cursor: pointer; transition: 0.3s; } img:hover { outline: var(--b) solid var(--c); outline-offset: var(--g); }

The trick is to create an outline that’s as thick as half the image size, then offset it by half the image size with a negative value. Add in some semi-transparency with the color and we have our overlay!

The rest is what happens on :hover. We update the outline and the transition between both outlines creates the cool hover effect. The same technique can also be used to create a fading effect where we don’t move the outline but make it transparent.

CodePen Embed Fallback

Instead of using half the image size in this one, I am using a very big outline thickness value (100vmax) while applying a CSS mask. With this, there’s no longer a need to know the image size — it trick works at all sizes!

You may face issues using 100vmax as a big value in Safari. If it’s the case, consider the previous trick where you replace the 100vmax with half the image size.

We can take things even further! For example, instead of simply clipping the extra outline, we can create shapes and apply a fancy reveal animation.

CodePen Embed Fallback

Cool right? The outline is what creates the yellow overlay. The clip-path clips the extra outline to get the star shape. Then, on hover, we make the color transparent.

Oh, you want hearts instead? We can certainly do that!

CodePen Embed Fallback

Imagine all the possible combinations we can create. All we have to do is to draw a shape with a CSS mask and/or clip-path and combine it with the outline trick. One solution, infinite possibilities!

And, yes, we can definitely animate this as well. Let’s not forget that clip-path is animatable and mask relies on gradients — something we covered in super great detail in the first two articles of this series.

CodePen Embed Fallback

I know, the animation is a bit glitchy. This is more of a demo to illustrate the idea rather than the “final product” to be used in a production site. We’d wanna optimize things for a more natural transition.

Here is a demo that uses mask instead. It’s the one I teased you with at the end of the last article:

CodePen Embed Fallback

Did you know that the outline property was capable of so much awesomeness? Add it to your toolbox for fancy image decorations!

Combine all the things!

Now that we have learned many tricks using gradients, masks, clipping, and outline, it’s time for the grand finale. Let’s cap off this series by combine all that we have learned the past few weeks to showcase not only the techniques, but demonstrate just how flexible and modular these approaches are.

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

If you were seeing these demos for the first time, you might assume that there’s a bunch of extra divs wrappers and pseudo-elements being used to pull them off. But everything is happening directly on the <img> element. It’s the only selector we need to get these advanced shapes and effects!

Wrapping up

Well, geez, thanks for hanging out with me in this three-part series the past few weeks. We explored a slew of different techniques that turn simple images into something eye-catching and interactive. Will you use everything we covered? Certainly not! But my hope is that this has been a good exercise for you to dig into advanced uses of CSS features, like gradients, mask, clip-path, and outline.

And we did everything with just one <img> element! No extra div wrappers and pseudo-elements. Sure, it’s a constraint we put on ourselves, but it also pushed us to explore CSS and try to find innovative solutions to common use cases. So, before pumping extra markup into your HTML, think about whether CSS is already capable of handling the task.

Fancy Image Decorations series

Fancy Image Decorations: Outlines and Complex Animations originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Holographic Trading Card Effect

Css Tricks - Wed, 10/26/2022 - 7:05am

Simon Goellner (@simeydotme)’s collection of Holographic Trading Cards have captured our attention.

Under the hood there is a suite of filter(), background-blend-mode(), mix-blend-mode(), and clip-path() combinations that have been painstakingly tweaked to reach the desired effect. I ended up using a little img { visibility: hidden; } in DevTools to get a better sense of each type of holographic effect.

Josh Dance (@JoshDance) replied with a breakdown of the effects that lets you manually control the inputs.

To Shared LinkPermalink on CSS-Tricks

Holographic Trading Card Effect originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Creating Animated, Clickable Cards With the :has() Relational Pseudo Class

Css Tricks - Tue, 10/25/2022 - 4:15am

The CSS :has() pseudo class is rolling out in many browsers with Chrome and Safari already fully supporting it. It’s often referred to it as “the parent selector” — as in, we can select style a parent element from a child selector — but there is so much more that :has() can help us solve. One of those things is re-inventing the clickable card pattern many of us love to use from time to time.

We’ll take a look at how :has() can help us handle linked cards, but first…

What is this :has() pseudo class?

There is already a bunch of great posts floating around that do an excellent job explaining what :has() is and what it’s used for, but it’s still new enough that we ought to say a few words about it here as well.

:has() is a relational pseudo class that’s part of the W3C Selectors Level 4 working draft. That’s what the parentheses are all about: matching elements that are related to — or, more accurately, contain — certain child elements.

/* Matches an article element that contains an image element */ article:has(img) { } /* Matches an article element with an image contained immediately within it */ article:has(> img) { }

So, you can see why we might want to call it a “parent” selector. But we can also combine it with other functional pseudo classes to get more specific. Say we want to style articles that do not contain any images. We can combine the relational powers of :has() with the negation powers of :not() to do that:

/* Matches an article without images */ article:not(:has(img)) { }

But that’s just the start of how we can combine powers to do more with :has(). Before we turn specifically to solving the clickable card conundrum, let’s look at a few ways we currently approach them without using :has().

How we currently handle clickable cards

There are three main approaches on how people create a fully clickable card these days and to fully understand the power of this pseudo class, it’s nice to have a bit of a round-up.

The “Link as a Wrapper” approach

This approach is something used quite frequently. I never use this approach but I created a quick demo to demonstrate it:

CodePen Embed Fallback

There are a lot of concerns here, especially when it comes to accessibility. When users navigate your website using the rotor function, they will hear the full text inside of that <a> element — the heading, the text, and the link. Someone might not want to sit through all that. We can do better. Since HTML5, we can nest block elements inside of an <a> element. But it never feels right to me, especially for this reason.


  • Quick to implement
  • Semantically correct


  • Accessibility concerns
  • Text not selectable
  • A lot of hassle to overwrite styles that you used on your default links
The JavaScript method

Using JavaScript, we can attach a link to our card instead of writing it in the markup. I found this great CodePen demo by costdev who also made the card text selectable in the process:

CodePen Embed Fallback

This approach has a lot of benefits. Our links are accessible on focus and we can even select text. But there are some drawbacks when it comes to styling. If we want to animate those cards, for example, we would have to add :hover styles on our main .card wrapper instead of the link itself. We also would not benefit from the animations when the links are in focus from keyboard tabbing.


  • Can be made perfectly accessible
  • Ability to select text


  • Requires JavaScript
  • Right clicking not possible (although could be fixed with some extra scripting)
  • Will require a lot of styling on the card itself which would not work when focussing the link
The ::after selector approach

This method requires us to set the card with relative positioning, then set absolute positioning on the link’s ::after pseudo selector of a link. This doesn’t require any JavaScript and is pretty easy to implement:

CodePen Embed Fallback

There are a few drawbacks here, especially when it comes to selecting text. Unless you provide a higher z-index on your card-body, you won’t be able to select text but if you do, be warned that clicking the text will not activate your link. Whether or not you want selectable text is up to you. I think it can be a UX issue, but it depends on the use-case. The text is still accessible to screen readers but my main problem with the method is the lack of animation possibilities.


  • Easy to implement
  • Accessible link without bloated text
  • Works on hover and focus


  • Text is not selectable
  • You can only animate the link as this is the element you’re hovering.
A new approach: Using ::after with :has()

Now that we’ve established the existing approaches for clickable cards, I want to show how introducing :has() to the mix solves most of those shortcomings.

In fact, let’s base this approach on the last one we looked at using ::after on the link element. We can actually use :has() there to overcome that approach’s animation constraints.

Let’s start with the markup:

<article> <figure> <img src="cat.webp" alt="Fluffy gray and white tabby kitten snuggled up in a ball." /> </figure> <div clas="article-body"> <h2>Some Heading</h2> <p>Curabitur convallis ac quam vitae laoreet. Nulla mauris ante, euismod sed lacus sit amet, congue bibendum eros. Etiam mattis lobortis porta. Vestibulum ultrices iaculis enim imperdiet egestas.</p> <a href="#"> Read more <svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M12.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-2.293-2.293a1 1 0 010-1.414z" clip-rule="evenodd" /> </svg> </a> </div> </article>

I will be keeping things as simple as possible by targeting elements in the CSS instead of classes.

For this demo, we’re going to add an image zoom and shadow to the card on hover, and animate the link with an arrow popping up and while changing the link’s text color. To make this easy, we’re going to add some custom properties scoped on our card. Here’s the basic styling:

/* The card element */ article { --img-scale: 1.001; --title-color: black; --link-icon-translate: -20px; --link-icon-opacity: 0; position: relative; border-radius: 16px; box-shadow: none; background: #fff; transform-origin: center; transition: all 0.4s ease-in-out; overflow: hidden; } /* The link's ::after pseudo */ article a::after { content: ""; position: absolute; inset-block: 0; inset-inline: 0; cursor: pointer; }

Great! We added an initial scale for the image (--img-scale: 1.001), the initial color of the card heading (--title-color: black) and some extra properties we will use to make our arrow pop out of the link. We’ve also set an empty state of the box-shadow declaration in order to animate it later . This sets up what we need for the clickable card right now, so let’s add some resets and styling to it by adding those custom properties to the elements we want to animate:

article h2 { margin: 0 0 18px 0; font-family: "Bebas Neue", cursive; font-size: 1.9rem; letter-spacing: 0.06em; color: var(--title-color); transition: color 0.3s ease-out; } article figure { margin: 0; padding: 0; aspect-ratio: 16 / 9; overflow: hidden; } article img { max-width: 100%; transform-origin: center; transform: scale(var(--img-scale)); transition: transform 0.4s ease-in-out; } article a { display: inline-flex; align-items: center; text-decoration: none; color: #28666e; } article a:focus { outline: 1px dotted #28666e; } article a .icon { min-width: 24px; width: 24px; height: 24px; margin-left: 5px; transform: translateX(var(--link-icon-translate)); opacity: var(--link-icon-opacity); transition: all 0.3s; } .article-body { padding: 24px; }

Let’s be kind to people and also add a screen reader class hidden behind the link:

.sr-only:not(:focus):not(:active) { clip: rect(0 0 0 0); clip-path: inset(50%); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; }

Our card is starting to look pretty sweet. It’s time to add a bit of magic to it. With the :has() pseudo class, we can now check if our link is hovered or focused, then update our custom properties and add a box-shadow. With this little chunk of CSS our card really comes to life:

/* Matches an article element that contains a hover or focus state */ article:has(:hover, :focus) { --img-scale: 1.1; --title-color: #28666e; --link-icon-translate: 0; --link-icon-opacity: 1; box-shadow: rgba(0, 0, 0, 0.16) 0px 10px 36px 0px, rgba(0, 0, 0, 0.06) 0px 0px 0px 1px; }

See what’s up there? Now we get the updated styles if any child element in the card is hovered or focused. And even though the link element is the only thing that can contain a hover or focus state in the ::after clickable card approach, we can use that to match the parent element and apply the transitions.

And there you have it. Just another powerful use case for the :has() selector. Not only can we match a parent element by declaring other elements as arguments, but we can match also use pseudos to match and style parents as well.


  • Accessible
  • Animatable
  • No JavaScript needed
  • Uses :hover on the correct element


  • Text is not easily selectable.
  • Browser support is limited to Chrome and Safari (it’s supported in Firefox behind a flag).

Here is a demo using this technique. You might notice an extra wrapper around the card, but that’s just me playing around with container queries, which is just one of those other fantastic things rolling out in all major browsers.

CodePen Embed Fallback

Got some other examples you wish to share? Other solutions or ideas are more than welcome in the comment section.

Creating Animated, Clickable Cards With the :has() Relational Pseudo Class originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Fancy Image Decorations: Masks and Advanced Hover Effects

Css Tricks - Fri, 10/21/2022 - 2:46am

Welcome to Part 2 of this three-part series! We are still decorating images without any extra elements and pseudo-elements. I hope you already took the time to digest Part 1 because we will continue working with a lot of gradients to create awesome visual effects. We are also going to introduce the CSS mask property for more complex decorations and hover effects.

Fancy Image Decorations series

Let’s turn to the first example we’re working on together…

The Postage Stamp CodePen Embed Fallback

Believe or not, all it takes to make postage stamp CSS effect is two gradients and a filter:

img { --r: 10px; /* control the radius of the circles */ padding: calc(2 * var(--r)); filter: grayscale(.4); background: radial-gradient(var(--r),#0000 98%,#fff) round calc(-1.5 * var(--r)) calc(-1.5 * var(--r)) / calc(3 * var(--r)) calc(3 * var(--r)), linear-gradient(#fff 0 0) no-repeat 50% / calc(100% - 3 * var(--r)) calc(100% - 3 * var(--r)); }

As we saw in the previous article, the first step is to make space around the image with padding so we can draw a background gradient and see it there. Then we use a combination of radial-gradient() and linear-gradient() to cut those circles around the image.

Here is a step-by-step illustration that shows how the gradients are configured:

CodePen Embed Fallback

Note the use of the round value in the second step. It’s very important for the trick as it ensures the size of the gradient is adjusted to be perfectly aligned on all the sides, no matter what the image width or height is.

From the specification: The image is repeated as often as will fit within the background positioning area. If it doesn’t fit a whole number of times, it is rescaled so that it does.

The Rounded Frame

Let’s look at another image decoration that uses circles…

CodePen Embed Fallback

This example also uses a radial-gradient(), but this time I have created circles around the image instead of the cut-out effect. Notice that I am also using the round value again. The trickiest part here is the transparent gap between the frame and the image, which is where I reach for the CSS mask property:

img { --s: 20px; /* size of the frame */ --g: 10px; /* the gap */ --c: #FA6900; padding: calc(var(--g) + var(--s)); background: radial-gradient(farthest-side, var(--c) 97%, #0000) 0 0 / calc(2 * var(--s)) calc(2 * var(--s)) round; mask: conic-gradient(from 90deg at calc(2 * var(--s)) calc(2 * var(--s)), #0000 25%, #000 0) calc(-1 * var(--s)) calc(-1 * var(--s)), linear-gradient(#000 0 0) content-box; }

Masking allows us to show the area of the image — thanks to the linear-gradient() in there — as well as 20px around each side of it — thanks to the conic-gradient(). The 20px is nothing but the variable --s that defines the size of the frame. In other words, we need to hide the gap.

Here’s what I mean:

CodePen Embed Fallback

The linear gradient is the blue part of the background while the conic gradient is the red part of the background. That transparent part between both gradients is what we cut from our element to create the illusion of an inner transparent border.

The Inner Transparent Border

For this one, we are not going to create a frame but rather try something different. We are going to create a transparent inner border inside our image. Probably not that useful in a real-world scenario, but it’s good practice with CSS masks.

CodePen Embed Fallback

Similar to the previous example, we are going to rely on two gradients: a linear-gradient() for the inner part, and a conic-gradient() for the outer part. We’ll leave a space between them to create the transparent border effect.

img { --b: 5px; /* the border thickness */ --d: 20px; /* the distance from the edge */ --_g: calc(100% - 2 * (var(--d) + var(--b))); mask: conic-gradient(from 90deg at var(--d) var(--d), #0000 25%, #000 0) 0 0 / calc(100% - var(--d)) calc(100% - var(--d)), linear-gradient(#000 0 0) 50% / var(--_g) var(--_g) no-repeat; }

You may have noticed that the conic gradient of this example has a different syntax from the previous example. Both are supposed to create the same shape, so why are they different? It’s because we can reach the same result using different syntaxes. This may look confusing at first, but it’s a good feature. You are not obliged to find the solution to achieve a particular shape. You only need to find one solution that works for you out of the many possibilities out there.

Here are four ways to create the outer square using gradients:

CodePen Embed Fallback

There are even more ways to pull this off, but you get the point.

There is no Best™ approach. Personally, I try to find the one with the smallest and most optimized code. For me, any solution that requires fewer gradients, fewer calculations, and fewer repeated values is the most suitable. Sometimes I choose a more verbose syntax because it gives me more flexibility to change variables and modify things. It comes with experience and practice. The more you play with gradients, the more you know what syntax to use and when.

Let’s get back to our inner transparent border and dig into the hover effect. In case you didn’t notice, there is a cool hover effect that moves that transparent border using a font-size trick. The idea is to define the --d variable with a value of 1em. This variables controls the distance of the border from the edge. We can transform like this:

--_d: calc(var(--d) + var(--s) * 1em)

…giving us the following updated CSS:

img { --b: 5px; /* the border thickness */ --d: 20px; /* the distance from the edge */ --o: 15px; /* the offset on hover */ --s: 1; /* the direction of the hover effect (+1 or -1)*/ --_d: calc(var(--d) + var(--s) * 1em); --_g: calc(100% - 2 * (var(--_d) + var(--b))); mask: conic-gradient(from 90deg at var(--_d) var(--_d), #0000 25%, #000 0) 0 0 / calc(100% - var(--_d)) calc(100% - var(--_d)), linear-gradient(#000 0 0) 50% / var(--_g) var(--_g) no-repeat; font-size: 0; transition: .35s; } img:hover { font-size: var(--o); }

The font-size is initially equal to 0 ,so 1em is also equal to 0 and --_d is be equal to --d. On hover, though, the font-size is equal to a value defined by an --o variable that sets the border’s offset. This, in turn, updates the --_d variable, moving the border by the offset. Then I add another variable, --s, to control the sign that decides whether the border moves to the inside or the outside.

CodePen Embed Fallback

The font-size trick is really useful if we want to animate properties that are otherwise unanimatable. Custom properties defined with @property can solve this but support for it is still lacking at the time I’m writing this.

The Frame Reveal

We made the following reveal animation in the first part of this series:

CodePen Embed Fallback

We can take the same idea, but instead of a border with a solid color we will use a gradient like this:

CodePen Embed Fallback

If you compare both codes you will notice the following changes:

  1. I used the same gradient configuration from the first example inside the mask property. I simply moved the gradients from the background property to the mask property.
  2. I added a repeating-linear-gradient() to create the gradient border.

That’s it! I re-used most of the same code we already saw — with super small tweaks — and got another cool image decoration with a hover effect.

/* Solid color border */ img { --c: #8A9B0F; /* the border color */ --b: 10px; /* the border thickness*/ --g: 5px; /* the gap on hover */ padding: calc(var(--g) + var(--b)); --_g: #0000 25%, var(--c) 0; background: conic-gradient(from 180deg at top var(--b) right var(--b), var(--_g)) var(--_i, 200%) 0 / 200% var(--_i, var(--b)) no-repeat, conic-gradient(at bottom var(--b) left var(--b), var(--_g)) 0 var(--_i, 200%) / var(--_i, var(--b)) 200% no-repeat; transition: .3s, background-position .3s .3s; cursor: pointer; } img:hover { --_i: 100%; transition: .3s, background-size .3s .3s; } /* Gradient color border */ img { --b: 10px; /* the border thickness*/ --g: 5px; /* the gap on hover */ background: repeating-linear-gradient(135deg, #F8CA00 0 10px, #E97F02 0 20px, #BD1550 0 30px); padding: calc(var(--g) + var(--b)); --_g: #0000 25%, #000 0; mask: conic-gradient(from 180deg at top var(--b) right var(--b), var(--_g)) var(--_i, 200%) 0 / 200% var(--_i, var(--b)) no-repeat, conic-gradient(at bottom var(--b) left var(--b), var(--_g)) 0 var(--_i, 200%) / var(--_i, var(--b)) 200% no-repeat, linear-gradient(#000 0 0) content-box; transition: .3s, mask-position .3s .3s; cursor: pointer; } img:hover { --_i: 100%; transition: .3s, mask-size .3s .3s; }

Let’s try another frame animation. This one is a bit tricky as it has a three-step animation:

CodePen Embed Fallback

The first step of the animation is to make the bottom edge bigger. For this, we adjust the background-size of a linear-gradient():

CodePen Embed Fallback

You are probably wondering why I am also adding the top edge. We need it for the third step. I always try to optimize the code I write, so I am using one gradient to cover both the top and bottom sides, but the top one is hidden and revealed later with a mask.

For the second step, we add a second gradient to show the left and right edges. But this time, we do it using background-position:

CodePen Embed Fallback

We can stop here as we already have a nice effect with two gradients but we are here to push the limits so let’s add a touch of mask to achieve the third step.

The trick is to make the top edge hidden until we show the bottom and the sides and then we update the mask-size (or mask-position) to show the top part. As I said previously, we can find a lot of gradient configurations to achieve the same effect.

Here is an illustration of the gradients I will be using:

CodePen Embed Fallback

I am using two conic gradients having a width equal to 200%. Both gradients cover the area leaving only the top part uncovered (that part will be invisible later). On hover, I slide both gradients to cover that part.

Here is a better illustration of one of the gradients to give you a better idea of what’s happening:

CodePen Embed Fallback

Now we put this inside the mask property and we are done! Here is the full code:

img { --b: 6px; /* the border thickness*/ --g: 10px; /* the gap */ --c: #0E8D94; padding: calc(var(--b) + var(--g)); --_l: var(--c) var(--b), #0000 0 calc(100% - var(--b)), var(--c) 0; background: linear-gradient(var(--_l)) 50%/calc(100% - var(--_i,80%)) 100% no-repeat, linear-gradient(90deg, var(--_l)) 50% var(--_i,-100%)/100% 200% no-repeat; mask: conic-gradient(at 50% var(--b),#0000 25%, #000 0) calc(50% + var(--_i, 50%)) / 200%, conic-gradient(at 50% var(--b),#000 75%, #0000 0) calc(50% - var(--_i, 50%)) / 200%; transition: .3s calc(.6s - var(--_t,.6s)) mask-position, .3s .3s background-position, .3s var(--_t,.6s) background-size, .4s transform; cursor: pointer; } img:hover { --_i: 0%; --_t: 0s; transform: scale(1.2); }

I have also introduced some variables to optimize the code, but you should be used to this right now.

What about a four-step animation? Yes, it’s possible!

CodePen Embed Fallback

No explanation for this because it’s your homework! Take all that you have learned in this article to dissect the code and try to articulate what it’s doing. The logic is similar to all the previous examples. The key is to isolate each gradient to understand each step of the animation. I kept the code un-optimized to make things a little easier to read. I do have an optimized version if you are interested, but you can also try to optimize the code yourself and compare it with my version for additional practice.

Wrapping up

That’s it for Part 2 of this three-part series on creative image decorations using only the <img> element. We now have a good handle on how gradients and masks can be combined to create awesome visual effects, and even animations — without reaching for extra elements or pseudo-elements. Yes, a single <img> tag is enough!

We have one more article in this series to go. Until then, here is a bonus demo with a cool hover effect where I use mask to assemble a broken image.

CodePen Embed Fallback Fancy Image Decorations series

Fancy Image Decorations: Masks and Advanced Hover Effects originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Responsive Animations for Every Screen Size and Device

Css Tricks - Thu, 10/20/2022 - 2:42am

Before I career jumped into development, I did a bunch of motion graphics work in After Effects. But even with that background, I still found animating on the web pretty baffling.

Video graphics are designed within a specific ratio and then exported out. Done! But there aren’t any “export settings” on the web. We just push the code out into the world and our animations have to adapt to whatever device they land on.

So let’s talk responsive animation! How do we best approach animating on the wild wild web? We’re going to cover some general approaches, some GSAP-specific tips and some motion principles. Let’s start off with some framing…

How will this animation be used?

Zach Saucier’s article on responsive animation recommends taking a step back to think about the final result before jumping into code.

Will the animation be a module that is repeated across multiple parts of your application? Does it need to scale at all? Keeping this in mind can help determine the method in which an animation should be scaled and keep you from wasting effort.

This is great advice. A huge part of designing responsive animation is knowing if and how that animation needs to scale, and then choosing the right approach from the start.

Most animations fall into the following categories:

  • Fixed: Animations for things like icons or loaders that retain the same size and aspect ratio across all devices. Nothing to worry about here! Hard-code some pixel values in there and get on with your day.
  • Fluid: Animations that need to adapt fluidly across different devices. Most layout animations fall into this category.
  • Targeted: Animations that are specific to a certain device or screen size, or change substantially at a certain breakpoint, such as desktop-only animations or interactions that rely on device-specific interaction, like touch or hover.

Fluid and targeted animations require different ways of thinking and solutions. Let’s take a look…

Fluid animation

As Andy Bell says: Be the browser’s mentor, not its micromanager — give the browser some solid rules and hints, then let it make the right decisions for the people that visit it. (Here are the slides from that presentation.)

Fluid animation is all about letting the browser do the hard work. A lot of animations can easily adjust to different contexts just by using the right units from the start. If you resize this pen you can see that the animation using viewport units scales fluidly as the browser adjusts:

CodePen Embed Fallback

The purple box even changes width at different breakpoints, but as we’re using percentages to move it, the animation scales along with it too.

Animating layout properties like left and top can cause layout reflows and jittery ‘janky’ animation, so where possible stick to transforms and opacity.

We’re not just limited to these units though — let’s take a look at some other possibilities.

SVG units

One of the things I love about working with SVG is that we can use SVG user units for animation which are responsive out of the box. The clue’s in the name really — Scalable Vector Graphic. In SVG-land, all elements are plotted at specific coordinates. SVG space is like an infinite bit of graph paper where we can arrange elements. The viewBox defines the dimensions of the graph paper we can see.

viewBox="0 0 100 50”

In this next demo, our SVG viewBox is 100 units wide and 50 units tall. This means if we animate the element by 100 units along the x-axis, it will always move by the entire width of its parent SVG, no matter how big or small that SVG is! Give the demo a resize to see.

CodePen Embed Fallback

Animating a child element based on a parent container’s width is a little tricker in HTML-land. Up until now, we’ve had to grab the parent’s width with JavaScript, which is easy enough when you’re animating from a transformed position, but a little fiddlier when you’re animating to somewhere as you can see in the following demo. If your end-point is a transformed position and you resize the screen, you’ll have to manually adjust that position. Messy… &#x1f914;

CodePen Embed Fallback

If you do adjust values on resize, remember to debounce, or even fire the function after the browser is finished resizing. Resize listeners fire a ton of events every second, so updating properties on each event is a lot of work for the browser.

But, this animation speed-bump is soon going to be a thing of the past! Drum roll please… &#x1f941;

After nearly 15 years as a highly-requested (impossible!?) feature, size-based Container Queries & units have shipped in both Chrome/Edge 105 & Safari 16! Firefox is not far behind.

(also: there's a prototype of style queries!)https://t.co/A2zgd9l4FC

— Mia (@TerribleMia) September 15, 2022

Container Units! Lovely stuff. At the time I’m writing this, they only work in Chrome and Safari — but maybe by the time you read this, we’ll have Firefox too. Check them out in action in this next demo. Look at those little lads go! Isn’t that exciting, animation that’s relative to the parent elements!

CodePen Embed Fallback

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

DesktopChromeFirefoxIEEdgeSafari105NoNo10516.0Mobile / TabletAndroid ChromeAndroid FirefoxAndroidiOS Safari107No10716.0 Fluid layout transitions with FLIP

As we mentioned earlier, in SVG-land every element is neatly placed on one grid and really easy to move around responsively. Over in HTML-land it’s much more complex. In order to build responsive layouts, we make use of a bunch of different positioning methods and layout systems. One of the main difficulties of animating on the web is that a lot of changes to layout are impossible to animate. Maybe an element needs to move from position relative to fixed, or some children of a flex container need to be smoothly shuffled around the viewport. Maybe an element even needs to be re-parented and moved to an entirely new position in the DOM.

Tricky, huh?

Well. The FLIP technique is here to save the day; it allows us to easily animate these impossible things. The basic premise is:

  • First: Grab the initial position of the elements involved in the transition.
  • Last: Move the elements and grab the final position.
  • Invert: Work out the changes between the first and last state and apply transforms to invert the elements back to their original position. This makes it look like the elements are still in the first position but they’re actually not.
  • Play: Remove the inverted transforms and animate to their faked first state to the last state.

Here’s a demo using GSAP’s FLIP plugin which does all the heavy lifting for you!

CodePen Embed Fallback

If you want to understand a little more about the vanilla implementation, head over to Paul Lewis’s blog post — he’s the brain behind the FLIP technique.

Fluidly scaling SVG

You got me… this isn’t really an animation tip. But setting the stage correctly is imperative for good animation! SVG scales super nicely by default, but we can control how it scales even further with preserveAspectRatio, which is mega handy when the SVG element’s aspect ratio and the viewBox aspect ratio are different. It works much in the same way as the background-position and background-size properties in CSS. The declaration is made up of an alignment value (background-position) and a Meet or Slice reference (background-size).

As for those Meet and Slice references — slice is like background size: cover, and meet is like background-size: contain.

  • preserveAspectRatio="MidYMax slice" — Align to the middle of the x-axis, the bottom of the y-axis, and scale up to cover the entire viewport.
  • preserveAspectRatio="MinYMin meet" — Align to the left of the x-axis, the top of the y-axis, and scale up while keeping the entire viewBox visible.
CodePen Embed Fallback

Tom Miller takes this a step further by using overflow: visible in CSS and a containing element to reveal “stage left” and “stage right” while keeping the height restricted:

For responsive SVG animations, it can be handy to make use of the SVG viewbox to create a view that crops and scales beneath a certain browser width, while also revealing more of the SVG animation to the right and left when the browser is wider than that threshold. We can achieve this by adding overflow visible on the SVG and teaming it up with a max-height wrapper to prevent the SVG from scaling too much vertically.

CodePen Embed Fallback Fluidly scaling canvas

Canvas is much more performant for complex animations with lots of moving parts than animating SVG or HTML DOM, but it’s inherently more complex too. You have to work for those performance gains! Unlike SVG that has lovely responsive units and scaling out of the box, <canvas> has to be bossed around and micromanaged a bit.

I like setting up my <canvas> so that it works much in the same way as SVG (I may be biased) with a lovely unit system to work within and a fixed aspect ratio. <canvas> also needs to be redrawn every time something changes, so remember to delay the redraw until the browser is finished resizing, or debounce!

CodePen Embed Fallback

George Francis also put together this lovely little library which allows you to define a Canvas viewBox attribute and preserveAspectRatio — exactly like SVG!

Targeted animation

You may sometimes need to take a less fluid and more directed approach to your animation. Mobile devices have a lot less real estate, and less animation-juice performance-wise than a desktop machine. So it makes sense to serve reduced animation to mobile users, potentially even no animation:

Sometimes the best responsive animation for mobile is no animation at all! For mobile UX, prioritize letting the user quickly consume content versus waiting for animations to finish. Mobile animations should enhance content, navigation, and interactions rather than delay it. Eric van Holtz

In order to do this, we can make use of media queries to target specific viewport sizes just like we do when we’re styling with CSS! Here’s a simple demo showing a CSS animation being handled using media queries and a GSAP animation being handled with gsap.matchMedia():

CodePen Embed Fallback

The simplicity of this demo is hiding a bunch of magic! JavaScript animations require a bit more setup and clean-up in order to correctly work at only one specific screen size. I’ve seen horrors in the past where people have just hidden the animation from view in CSS with opacity: 0, but the animation’s still chugging away in the background using up resources. &#x1f631;

If the screen size doesn’t match anymore, the animation needs to be killed and released for garbage collection, and the elements affected by the animation need to be cleared of any motion-introduced inline styles in order to prevent conflicts with other styling. Up until gsap.matchMedia(), this was a fiddly process. We had to keep track of each animation and manage all this manually.

gsap.matchMedia() instead lets you easily tuck your animation code into a function that only executes when a particular media query matches. Then, when it no longer matches, all the GSAP animations and ScrollTriggers in that function get reverted automatically. The media query that the animations are popped into does all the hard work for you. It’s in GSAP 3.11.0 and it’s a game changer!

We aren’t just constrained to screen sizes either. There are a ton of media features out there to hook into!

(prefers-reduced-motion) /* find out if the user would prefer less animation */ (orientation: portrait) /* check the user's device orientation */ (max-resolution: 300dpi) /* check the pixel density of the device */

In the following demo we’ve added a check for prefers-reduced-motion so that any users who find animation disorienting won’t be bothered by things whizzing around.

CodePen Embed Fallback

And check out Tom Miller’s other fun demo where he’s using the device’s aspect ratio to adjust the animation:

CodePen Embed Fallback Thinking outside of the box, beyond screen sizes

There’s more to thinking about responsive animation than just screen sizes. Different devices allow for different interactions, and it’s easy to get in a bit of a tangle when you don’t consider that. If you’re creating hover states in CSS, you can use the hover media feature to test whether the user’s primary input mechanism can hover over elements.

@media (hover: hover) { /* CSS hover state here */ }

Some advice from Jake Whiteley:

A lot of the time we base our animations on browser width, making the naive assumption that desktop users want hover states. I’ve personally had a lot of issues in the past where I would switch to desktop layout >1024px, but might do touch detection in JS – leading to a mismatch where the layout was for desktops, but the JS was for mobiles. These days I lean on hover and pointer to ensure parity and handle ipad Pros or windows surfaces (which can change the pointer type depending on whether the cover is down or not)

/* any touch device: */ (hover: none) and (pointer: coarse) /* iPad Pro */ (hover: none) and (pointer: coarse) and (min-width: 1024px)

I’ll then marry up my CSS layout queries and my JavaScript queries so I’m considering the input device as the primary factor supported by width, rather than the opposite.

ScrollTrigger tips

If you’re using GSAP’s ScrollTrigger plugin, there’s a handy little utility you can hook into to easily discern the touch capabilities of the device: ScrollTrigger.isTouch.

  • 0 – no touch (pointer/mouse only)
  • 1 – touch-only device (like a phone)
  • 2 – device can accept touch input and mouse/pointer (like Windows tablets)
if (ScrollTrigger.isTouch) { // any touch-capable device... } // or get more specific: if (ScrollTrigger.isTouch === 1) { // touch-only device }

Another tip for responsive scroll-triggered animation…

The following demo below is moving an image gallery horizontally, but the width changes depending on screen size. If you resize the screen when you’re halfway through a scrubbed animation, you can end up with broken animations and stale values. This is a common speedbump, but one that’s easily solved! Pop the calculation that’s dependent on screen size into a functional value and set invalidateOnRefresh:true. That way, ScrollTrigger will re-calculate that value for you when the browser resizes.

CodePen Embed Fallback Bonus GSAP nerd tip!

On mobile devices, the browser address bar usually shows and hides as you scroll. This counts as a resize event and will fire off a ScrollTrigger.refresh(). This might not be ideal as it can cause jumps in your animation. GSAP 3.10 added ignoreMobileResize. It doesn’t affect how the browser bar behaves, but it prevents ScrollTrigger.refresh() from firing for small vertical resizes on touch-only devices.

ScrollTrigger.config({ ignoreMobileResize: true }); Motion principles

I thought I’d leave you with some best practices to consider when working with motion on the web.

Distance and easing

A small but important thing that’s easy to forget with responsive animation is the relationship between speed, momentum, and distance! Good animation should mimic the real world to feel believable, and it takes a longer in the real world to cover a larger distance. Pay attention to the distance your animation is traveling, and make sure that the duration and easing used makes sense in context with other animations.

You can also often apply more dramatic easing to elements with further to travel to show the increased momentum:

CodePen Embed Fallback

For certain use cases it may be helpful to adjust the duration more dynamically based on screen width. In this next demo we’re making use of gsap.utils to clamp the value we get back from the current window.innerWidth into a reasonable range, then we’re mapping that number to a duration.

CodePen Embed Fallback Spacing and quantity

Another thing to keep in mind is the spacing and quantity of elements at different screen sizes. Quoting Steven Shaw:

If you have some kind of environmental animation (parallax, clouds, trees, confetti, decorations, etc) that are spaced around the window, make sure that they scale and/or adjust the quantity depending on screen size. Large screens probably need more elements spread throughout, while small screens only need a few for the same effect.

I love how Opher Vishnia thinks about animation as a stage. Adding and removing elements doesn’t just have to be a formality, it can be part of the overall choreography.

When designing responsive animations, the challenge is not how to cram the same content into the viewport so that it “fits”, but rather how to curate the set of existing content so it communicates the same intention. That means making a conscious choice of which pieces content to add, and which to remove. Usually in the world of animation things don’t just pop in or out of the frame. It makes sense to think of elements as entering or exiting the “stage”, animating that transition in a way that makes visual and thematic sense.

CodePen Embed Fallback

And that’s the lot. If you have any more responsive animation tips, pop them in the comment section. If there’s anything super helpful, I’ll add them to this compendium of information!


One more note from Tom Miller as I was prepping this article:

I’m probably too late with this tip for your responsive animations article, but I highly recommend “finalize all the animations before building”. I’m currently retrofitting some site animations with “mobile versions”. Thank goodness for gsap.matchMedia… but I sure wish we’d known there’d be separate mobile layouts/animations from the beginning.

I think we all appreciate that this tip to “plan ahead” came at the absolute last minute. Thanks, Tom, and best of luck with those retrofits.

Responsive Animations for Every Screen Size and Device originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

How to Make a Folder “Slit” Effect With CSS

Css Tricks - Wed, 10/19/2022 - 2:56am

When you put something — say a regular sheet of paper — in a manilla folder, a part of that thing might peek out of the folder a little bit. The same sort of thing with a wallet and credit cards. The cards poke out just a smidge so you can get a quick glance of which cards you’re carrying.

Credit: Stephen Phillips on Unsplash

I call this sort of thing a “slit”. A slit is where we create the illusion of an opening through which we can tease a visual element peeking out of it. And we can do that in CSS!

The crucial part of the design is the shadow, which is what gives the visual cue of there being a slit. Then there’s the cover for the slit which provides the space for the exhibited element to peek through from under.

Here’s what we’re going to make together:

CodePen Embed Fallback Let’s begin with creating the shadow

You might be surprised that the shadow in the example is not created with an actual CSS shadow, like box-shadow or a drop-shadow() filter. Instead, the shadow is a separate element in itself, dark and blurred out. This is important in order to make the design more adaptable, both in its default and animated states.

The cover is the other element in the design. The cover is what I call the element that overlaps the shadow. Here’s a figure depicting how the shadow and cover come together.

The shadow is made from a small upright rectangle that has a gradient background. The gradient is darker in the middle. So when the element is blurred, it creates a shadow that’s darker in the middle; hence more dimensional.

CodePen Embed Fallback

Now, the left half of the recreated shadow is covered with a rectangle on top, colored exactly the same as the background of its container.

Both the cover and the shadow are then moved to the left ever so slightly so it appears to be layered

Working on the cover

For the cover to blend with the design’s background, its background color is inherited from its containing element. Alternatively, you can also try to blend the cover to its background using standards like CSS masks and blend modes, depending on your design choices and requirements.

CodePen Embed Fallback

To learn some basics on how these standards might be applied, you can refer to these articles: Sarah Drasner’s “Masking vs. Clipping: When to Use Each” provides an excellent primer on masks. I’ve also written about CSS blend modes in this article where you can brush up on the topic.

In the source code of my example, you’ll notice that I aligned and stacked the elements inside the <main> element using CSS Grid, which is a layout standard I often use in my demos. If you’re recreating a similar design, use a layout method that fits the best for your application to align the different parts of the design. In this case, I’ve set up a single-column grid on the <main> element which allows me to center align the cover, shadow, and image.

What CSS Grid also allows me to do is set all three of those divs so they are all full-width in the <main> container:

main > div { grid-area: 1 / 1; }

This gets everything to stack on top of one another. Normally, we work hard to avoid covering elements with other elements in a grid. But this example relies on it. I’ve given the .slit-cover at width of 50% which naturally reveals the image underneath it. From there, I set a transform on it that moves it 50% in the negative direction, plus the small amount I shifted the shadow earlier (25px) to make sure that is revealed as well.

.slit-cover { width: 50%; transform: translatex(calc(-50% - 25px)); /* etc. */ }

And there we have it! A pretty natural-looking slit that mimics something peeking out of a folder, wallet, or whatever.

CodePen Embed Fallback

There are more ways to do this! For one, Flexbox can get elements to line up in a row and align in the center like this. There are lots of ways to get things side-by-side. And maybe you have a way to use the box-shadow property, drop-shadow() filter, or even SVG filters to get the same sort of shadow effect that really sells the illusion.

And you can totally riff on this to get your own look and feel. For example, try swapping the position of the shadow and image. Or play with the color combinations and change the blur() filter value. The shape of the cover and the shadow can also be tweaked — I bet you can create a curved shadow instead of a straight one and share it with us in the comments!

How to Make a Folder “Slit” Effect With CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Pure CSS Bezier Curve Motion Paths

Css Tricks - Mon, 10/17/2022 - 5:30am

Are you a Bezier curve lover like I am?

CodePen Embed Fallback

Besides being elegant, Bezier curves have nice mathematical properties due to their definition and construction. No wonder they are widely used in so many areas:

  • As a drawing/design tool: They are often refered to as “paths” in vector drawing software.
  • As a format of representing curves: They are used in SVG, fonts and many other vector graphic formats.
  • As a mathematical function: Often used to control animation timing.

Now, how about using Bezier curves as motion paths with CSS?

Quick Recap

Depending on the context, when referring to a “Bezier curve”, we often assume a 2D cubic Bezier curve.

Such a curve is defined by four points:

MarianSigler, Public domain, via Wikimedia Commons

Note: In this article, we generally refer to P0 and P3 as endpoints, P1 and P2 as control points.

The word “cubic” means the underlying function of the curve is a cubic polynomial. There are also “quadratic” Bezier curves, which are similar, but with one fewer control point.

The Problem

Say you are given an arbitrary 2D cubic Beizer curve, how would you animate an element with pure CSS animation, such that it moves precisely along the curve?

As an example, how would you recreate this animation?

CodePen Embed Fallback

In this article we will explore three methods with different flavors. For each solution we will present an interactive demo, then explain how it works. There are lots of mathematical calculations and proofs behind the scene, but don’t worry, we will not go very deep.

Let’s start!

Method 1: Time Warp

Here’s the basic idea:

  • Set up @keyframes to move the element from one endpoint of the curve to the other.
  • Distort the time for each coordinate individually, using animation-timing-function.

Note: There are lots of examples and explanations in Temani Afif’s article (2021).

Using the cubic-bezier() function with correct parameters, we can create a motion path of any cubic Bezier curve:

CodePen Embed Fallback

This demo shows a pure CSS animation. Yet canvas and JavaScript are used, which serve two purposes:

  • Visualize the underlying Bezier curve (red curve).
  • Allow adjusting the curve with the typical “path” UI.

You can drag the two endpoints (black dots) and the two control points (black squares). The JavaScript code will update the animation accordingly, by updating a few CSS variables.

Note: Here’s a pure CSS version for reference.

How it works

Suppose the desired cubic Bezier curve is defined by four points: p0, p1, p2, and p3. We set up CSS rules as following:

/* pseudo CSS code */ div { animation-name: move-x, move-y; /* Define: f(x, a, b) = (x - a) / (b - a) qx1 = f(p1.x, p0.x, p3.x) qx2 = f(p2.x, p0.x, p3.x) qy1 = f(p1.y, p0.y, p3.y) qy2 = f(p2.y, p0.y, p3.y) */ animation-timing-function: cubic-bezier(1/3, qx1, 2/3, qx1), cubic-bezier(1/3, qy1, 2/3, qy2); } @keyframes move-x { from { left: p0.x; } to { left: p3.x; } } @keyframes move-y { from { top: p0.y; } to { top: p3.y; } }

The @keyframes rules move-x and move-y determine the starting and finishing locations of the element. In animation-timing-function we have two magical cubic-bezier() functions, the parameters are calculated such that both top and left always have the correct values at any time.

I’ll skip the math, but I drafted a brief proof here, for your curious math minds.


This method should work well for most cases. You can even make a 3D cubic Bezier curve, by introducing another animation for the z value.

However there are a few minor caveats:

  • It does not work when both endpoints lie on a horizontal or vertical line, because of the division-by-zero error.

Note: In practice, you can just add a tiny offset as a workaround.

  • It does not support Bezier curves with an order higher than 3.
  • Options for animation timing are limited.
    • We use 1/3 and 2/3 above to achieve a linear timing.
    • You can tweak both values to adjust the timing, but it is limited compared with other methods. More on this later.
Method 2: Competing Animations

As a warm-up, imagine an element with two animations:

div { animation-name: move1, move2; }

What is the motion path of the element, if the animations are defined as following:

@keyframes move1 { to { left: 256px; } } @keyframes move2 { to { top: 256px; } }

As you may have guessed, it moves diagonally:

CodePen Embed Fallback

Now, what if the animations are defined like this instead:

@keyframes move1 { to { transform: translateX(256px); } } @keyframes move2 { to { transform: translateY(256px); } }

“Aha, you cannot trick me!” you might say, as you noticed that both animations are changing the same property, “move2 must override move1 like this:”

CodePen Embed Fallback

Well, earlier I had thought so, too. But actually we get this:

CodePen Embed Fallback

The trick is that move2 does not have a from frame, which means the starting position is animated by move1.

In the following demo, the starting position of move2 is visualized as the moving blue dot:

CodePen Embed Fallback Quadratic Bezier Curves

The demo right above resembles the construction of a quadratic Bezier curve:

Phil Tregoning, Public domain, via Wikimedia Commons

But they look different. The construction has three linearly moving dots (two green, one black), but our demo has only two (the blue dot and the target element).

Actually the motion path in the demo is a quadratic Bezier curve, we just need to tune the keyframes carefully. I will skip the math and just reveal the magic:

Suppose a quadratic Bezier curve is defined by points p0, p1, and p2. In order to move an element along the curve, we do the following:

/* pseudo-CSS code */ div { animation-name: move1, move2; } @keyframes move1 { from { transform: translate3d(p0.x, p0.y, p0.z); } /* define q1 = (2 * p1 - p2) */ to { transform: translate3d(q1.x, q1.y, q1.z); } } @keyframes move2 { to { transform: translate3d(p2.x, p2.y, p2.z); } } CodePen Embed Fallback

Similar to the demo of Method 1, you can view or adjust the curve. Additionally, the demo also shows two more pieces of information:

  • The mathematical construction (gray moving parts)
  • The CSS animations (blue parts)

Both can be toggled using the checkboxes.

Cubic Bezier Curves

This method works for cubic Bezier curves as well. If the curve is defined by points p0, p1, p2, and p3. The animations should be defined like this:

/* pseudo-CSS code */ div { animation-name: move1, move2, move3; } @keyframes move1 { from { transform: translate3d(p0.x, p0.y, p0.z); } /* define q1 = (3 * p1 - 3 * p2 + p3) */ to { transform: translate3d(q1.x, q1.y, q1.z); } } @keyframes move2 { /* define q2 = (3 * p2 - 2 * p3) */ to { transform: translate3d(q2.x, q2.y, q2.z); } } @keyframes move3 { to { transform: translate3d(p3.x, p3.y, p3.z); } } CodePen Embed Fallback Extensions

What about 3D Bezier Curves? Actually, the truth is, all the previous examples were 3D curves, we just never bothered with the z values.

What about higher-order Bezier curves? I am 90% sure that the method can be naturally extended to higher orders. Please let me know if you have worked out the formula for fourth-order Bezier curves, or even better, a generic formula for Bezier curves of order N.

Method 3: Standard Bezier Curve Construction

The mathematical construction of Bezier Curves already gives us a good hint.

Phil Tregoning, Public domain, via Wikimedia Commons

Step-by-step, we can determine the coordinates of all moving dots. First, we determine the location of the green dot that is moving between p0 and p1:

@keyframes green0 { from { --green0x: var(--p0x); --green0y: var(--p0y); } to { --green0x: var(--p1x); --green0y: var(--p1y); } }

Additional green dots can be constructed in a similar way.

Next, we can determine the location of a blue dot like this:

@keyframes blue0 { from { --blue0x: var(--green0x); --blue0y: var(--green0y); } to { --blue0x: var(--green1x); --blue0y: var(--green1y); } }

Rinse and repeat, eventually we will get the desired curve.

CodePen Embed Fallback

Similar to Method 2, with this method we can easily build a 3D Bezier Curve. It is also intuitive to extend the method for higher-order Bezier curves.

The only downside is the usage of @property, which is not supported by all browsers.

Animation Timing

All the examples so far have the “linear” timing, what about easing or other timing functions?

Note: By “linear” we mean the variable t of the curve linearly changes from 0 to 1. In other words, t is the same as animation progress.

animation-timing-function is never used in Method 2 and Method 3. Like other CSS animations, we can use any supported timing function here, but we need to apply the same function for all animations (move1, move2, and move3) at the same time.

Here’s an example of animation-timing-function: cubic-bezier(1, 0.1, 0, 0.9):

CodePen Embed Fallback

And here’s how it looks like with animation-timing-function: steps(18, end):

CodePen Embed Fallback

On the other hand, Method 1 is trickier, because it already uses a cubic-bezier(u1, v1, u2, v2) timing function. In the examples above we have u1=1/3 and u2=2/3. In fact we can tweak the timing by changing both parameters. Again, all animations (e.g., move-x and move-y) must have the same values of u1 and u2.

Here’s how it looks like when u1=1 and u2=0:

CodePen Embed Fallback

With Method 2, we can achieve exactly the same effect by setting animation-timing-function to cubic-bezier(1, 0.333, 0, 0.667):

CodePen Embed Fallback

In fact, it works in a more general way:

Suppose that we are given a cubic Bezier curve, and we created two animations for the curve with Method 1 and Method 2 respectively. For any valid values of u1 and u2, the following two setups have the same animation timing:

  • Method 1 with animation-timing-function: cubic-bezier(u1, *, u2, *).
  • Method 2 with animation-timing-function: cubic-bezier(u1, 1/3, u2, 2/3).

Now we see why Method 1 is “limited”: with Method 1 we can only cubic-bezier() with two parameters, but with Method 2 and Method 3 we can use any CSS animation-timing-function.


In this article, we discussed 3 different methods of moving elements precisely along a Bezier curve, using only CSS animations.

While all 3 methods are more or less practical, they have their own pros and cons:

  • Method 1 might be more intuitive for those familiar with the timing function hack. But it is less flexible with animation timing.
  • Method 2 has very simple CSS rules. Any CSS timing function can be applied directly. However, it could be hard to remember the formulas.
  • Method 3 make more sense for those familiar with the math construction of Bezier curves. Animation timing is also flexible. On the other hand, not all modern browsers are supported, due the usage of @property.

That’s all! I hope you find this article interesting. Please let me know your thoughts!

Pure CSS Bezier Curve Motion Paths originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Behind the CSScenes, October 2022

Css Tricks - Fri, 10/14/2022 - 11:40am

Well, hey, welcome back to Behind the CSScenes! These posts are like little check-ins we’re doing each month to give you a peek behind what we’re doing here at CSS-Tricks, as well as a chance for us to pause and celebrate a few things.

Last month, we shared a small taste of a redesign for this very site. Thanks to all the folks who wrote in to comment on it! Seems the overwhelming response is pretty dang positive, though the background color was a mixed bag of reactions.

There’s more work to do, of course! This month, we have a little more to share with you on the development side of things, plus a roundup of some recent activity around here. So, let’s dial in Haley Mills for the latest.

Content updates

[Haley:] September was a busy month for our team! We published 16 articles by guest authors and another 15 by folks on our team. In addition to these, we’ve been updating many of the older articles, including adding freshly-linked resources. We’ve already updated over 50 articles and will continue these efforts as part of our day-to-day work. Thank you to the team and the awesome authors who contributed this content!

To build on our efforts to provide front-end developers with the tools they need, I’m also super excited to share that we are starting to kick the tires on new guides. Guides have been a free, helpful resource to the CSS-Tricks Community since the first one was published in 2019, and we’ve known from day 1 that we need to keep this tradition going. Since this is a new process for our team, we want to ensure that the workflow for authors is completely snag-free before opening it up to the public to apply. Until then, we will be working with hand-selected authors to bring you new guides on a variety of topics.

Have a suggestion for a guide that you’d love to see? Let us know in the comments!

Finally, you might’ve heard the news that CloudWays is joining DigitalOcean and is offering a $50 credit to folks in our community! While our top priority will always be to provide platform-agnostic resources to CSS-Tricks readers, you can expect to see helpful content about CloudWays in the future because we truly believe that their managed solution could be a great fit for the community.

Thanks for reading the content updates! Next up we have our senior web developer, David Berg, with an update on the back-end work we’re doing to move CSS-Tricks to a new CMS.

What’s happening on the back end

[David Berg:] The DigitalOcean team is actively working to pluck CSS-Tricks from WordPress and drop it into the same hand-rolled CMS we use for our other sites, including DigitalOcean’s library of tutorials. Don’t worry! CSS-Tricks will still be the same standalone site at the same domain, hyphenated and all. But it’s a ton of work, as you might imagine!

If anything has been challenging so far, it’s been aligning the WordPress data from the current site with the structure of our internal system. Our team currently uses a properly vetted, maintained, and organized PostgreSQL database that interfaces with the client through an array of in-repository services over which we maintain tight code control and quality. The WordPress database structure is unintuitive — at least to me and our team — and has required our team to find obscure and maybe overly complex solutions to mash these things together.

That said, migrating CSS-Tricks content over to our in-house solution allows us to ensure the integrity and future-proofing of complex database relationships. Through this process, we can slim down the time it takes to query the database, improve efficiencies of three (or more)-dimensional relationships, and accurately model new relationships according to new features we might develop down the road.

In short, that means we will no longer be reliant on a monolithic WordPress instance to serve a response to every request. We can statically export all the publicly accessible content to a CDN, with the services handling edit operations only when needed.

It’s easier to submit article proposals!

[Haley:] Speaking of a more robust back end architecture, something else happening behind the scenes is a new form for guest authors submitting article proposals to us for publication.

We used a form before this one, but we had it tied up with Jira in a way that helps us manage the proposals and keep track of where they are in the editing flow. That integration was crumbling right before our eyes, so we went with a Typeform-powered version instead.

While it might seem like a fairly minor thing, it’s a big deal as far as making it easier to share your proposals and making sure nothing falls through the cracks — so we have fresh new front-end content to publish for you on a consistent basis!

Oh, and if you happen to submit a proposal (and you should!) please let us know if you see any opportunities for us to make it even easier and more helpful.

Passing it back to Geoff with my favorite part of these updates: author highlights!

Some fresh new faces around here

[Geoff:] The articles you read here at CSS-Tricks are written by folks like yourself. It’s amazing just how gosh darned smart this community is and all the ideas that get passed around here. In fact, we welcomed 5 new voices this past month:

What a great bunch, right? Give ‘em all some love for taking time out of their busy lives to share their wisdom and clever tricks with the rest of us. And a shout out to familiar faces, like Temani Afif, Preethi, Ollie Williams, and Mojtaba Seyedi for all the hard work they continue to do that keeps pushing this thing we call front-end development forward.

High fives to all these folks, and to you for reading. ✋ We wouldn’t be doing this without y’all.

Behind the CSScenes, October 2022 originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Fancy Image Decorations: Single Element Magic

Css Tricks - Fri, 10/14/2022 - 5:37am

As the title says, we are going to decorate images! There’s a bunch of other articles out there that talk about this, but what we’re covering here is quite a bit different because it’s more of a challenge. The challenge? Decorate an image using only the <img> tag and nothing more.

That right, no extra markup, no divs, and no pseudo-elements. Just the one tag.

Sounds difficult, right? But by the end of this article — and the others that make up this little series — I’ll prove that CSS is powerful enough to give us great and stunning results despite the limitation of working with a single element.

Fancy Image Decorations series Let’s start with our first example CodePen Embed Fallback

Before digging into the code let’s enumerate the possibilities for styling an <img> without any extra elements or pseudo-elements. We can use border, box-shadow, outline, and, of course, background. It may look strange to add a background to an image because we cannot see it as it will be behind the image — but the trick is to create space around the image using padding and/or border and then draw our background inside that space.

I think you know what comes next since I talked about background, right? Yes, gradients! All the decorations we are going to make rely on a lot of gradients. If you’ve followed me for a while, I think this probably comes as no surprise to you at all. &#x1f601;

Let’s get back to our first example:

img { --s: 10px; /* control the size */ padding: var(--s); border: calc(2 * var(--s)) solid #0000; outline: 1px solid #000; outline-offset: calc(-1 * var(--s)); background: conic-gradient(from 90deg at 1px 1px, #0000 25%, #000 0); }

We are defining padding and a transparent border using the variable --s to create a space around our image equal to three times that variable.

Why are we using both padding and border instead of one or the other? We can get by using only one of them but I need this combination for my gradient because, by default, the initial value of background-clip is border-box and background-origin is equal to padding-box.

Here is a step-by-step illustration to understand the logic:

CodePen Embed Fallback

Initially, we don’t have any borders on the image, so our gradient will create two segments with 1px of thickness. (I am using 3px in this specific demo so it’s easier to see.) We add a colored border and the gradient still gives us the same result inside the padding area (due to background-origin) but it repeats behind the border. If we make the color of the border transparent, we can use the repetition and we get the frame we want.

The outline in the demo has a negative offset. That creates a square shape at the top of the gradient. That’s it! We added a nice decoration to our image using one gradient and an outline. We could have used more gradients! But I always try to keep my code as simple as possible and I found that adding an outline is better that way.

Here is a gradient-only solution where I am using only padding to define the space. Still the same result but with a more complex syntax.

CodePen Embed Fallback

Let’s try another idea:

CodePen Embed Fallback

For this one, I took the previous example removed the outline, and applied a clip-path to cut the gradient on each side. The clip-path value is a bit verbose and confusing but here is an illustration to better see its points:

I think you get the main idea. We are going to combine backgrounds, outlines, clipping, and some masking to achieve different kinds of decorations. We are also going to consider some cool hover animations as an added bonus! What we’ve looked at so far is merely a small overview of what’s coming!

The Corner-Only Frame CodePen Embed Fallback

This one takes four gradients. Each gradient covers one corner and, on hover, we expand them to create a full frame around the image. Let’s dissect the code for one of the gradients:

--b: 5px; /* border thickness */ background: conic-gradient(from 90deg at top var(--b) left var(--b), #0000 90deg, darkblue 0) 0 0; background-size: 50px 50px; background-repeat: no-repeat;

We are going to draw a gradient with a size equal to 50px 50px and place it at the top-left corner (0 0). For the gradient’s configuration, here’s a step-by-step illustration showing how I reached that result.

CodePen Embed Fallback

We tend to think that gradients are only good for transitioning between two colors. But in reality, we can do so much more with them! They are especially useful when it comes to creating different shapes. The trick is to make sure we have hard stops between colors — like in the example above — rather than smooth transitions:

#0000 25%, darkblue 0

This is basically saying: “fill the gradient with a transparent color until 25% of the area, then fill the remaining area with darkblue.

You might be scratching your head over the 0 value. It’s a little hack to simplify the syntax. In reality, we should use this to make a hard stop between colors:

#0000 25%, darkblue 25%

That is more logical! The transparent color ends at 25% and darkblue starts exactly where the transparency ends, making a hard stop. If we replace the second one with 0, the browser will do the job for us, so it is a slightly more efficient way to go about it.

Somewhere in the specification, it says:

if a color stop or transition hint has a position that is less than the specified position of any color stop or transition hint before it in the list, set its position to be equal to the largest specified position of any color stop or transition hint before it.

0 is always smaller than any other value, so the browser will always convert it to the largest value that comes before it in the declaration. In our case, that number is 25%.

Now, we apply the same logic to all the corners and we end with the following code:

img { --b: 5px; /* border thickness */ --c: #0000 90deg, darkblue 0; /* define the color here */ padding: 10px; background: conic-gradient(from 90deg at top var(--b) left var(--b), var(--c)) 0 0, conic-gradient(from 180deg at top var(--b) right var(--b), var(--c)) 100% 0, conic-gradient(from 0deg at bottom var(--b) left var(--b), var(--c)) 0 100%, conic-gradient(from -90deg at bottom var(--b) right var(--b), var(--c)) 100% 100%; background-size: 50px 50px; /* adjust border length here */ background-repeat: no-repeat; }

I have introduced CSS variables to avoid some redundancy as all the gradients use the same color configuration.

For the hover effect, all I’m doing is increasing the size of the gradients to create the full frame:

img:hover { background-size: 51% 51%; }

Yes, it’s 51% instead of 50% — that creates a small overlap and avoids possible gaps.

Let’s try another idea using the same technique:

CodePen Embed Fallback

This time we are using only two gradients, but with a more complex animation. First, we update the position of each gradient, then increase their sizes to create the full frame. I also introduced more variables for better control over the color, size, thickness, and even the gap between the image and the frame.

img { --b: 8px; /* border thickness*/ --s: 60px; /* size of the corner*/ --g: 14px; /* the gap*/ --c: #EDC951; padding: calc(var(--b) + var(--g)); background-image: conic-gradient(from 90deg at top var(--b) left var(--b), #0000 25%, var(--c) 0), conic-gradient(from -90deg at bottom var(--b) right var(--b), #0000 25%, var(--c) 0); background-position: var(--_p, 0%) var(--_p, 0%), calc(100% - var(--_p, 0%)) calc(100% - var(--_p, 0%)); background-size: var(--s) var(--s); background-repeat: no-repeat; transition: background-position .3s var(--_i,.3s), background-size .3s calc(.3s - var(--_i, .3s)); } img:hover { background-size: calc(100% - var(--g)) calc(100% - var(--g)); --_p: calc(var(--g) / 2); --_i: 0s; }

Why do the --_i and --_p variables have an underscore in their name? The underscores are part of a naming convention I use to consider “internal” variables used to optimize the code. They are nothing special but I want to make a difference between the variables we adjust to control the frame (like --b, --c, etc.) and the ones I use to make the code shorter.

The code may look confusing and not easy to grasp but I wrote a three-part series where I detail such technique. I highly recommend reading at least the first article to understand how I reached the above code.

Here is an illustration to better understand the different values:

The Frame Reveal

Let’s try another type of animation where we reveal the full frame on hover:

CodePen Embed Fallback

Cool, right? And you if you look closely, you will notice that the lines disappear in the opposite direction on mouse out which makes the effect even more fancy! I used a similar effect in a previous article.

CodePen Embed Fallback

But this time, instead of covering all the element, I cover only a small portion by defining a height to get something like this:

CodePen Embed Fallback

This is the top border of our frame. We repeat the same process on each side of the image and we have our hover effect:

img { --b: 10px; /* the border thickness*/ --g: 5px; /* the gap on hover */ --c: #8A9B0F; padding: calc(var(--g) + var(--b)); --_g: no-repeat linear-gradient(var(--c) 0 0); background: var(--_g) var(--_i, 0%) 0, var(--_g) 100% var(--_i, 0%), var(--_g) calc(100% - var(--_i, 0%)) 100%, var(--_g) 0 calc(100% - var(--_i, 0%)); background-size: var(--_i, 0%) var(--b),var(--b) var(--_i, 0%); transition: .4s, background-position 0s; cursor: pointer; } img:hover { --_i: 100%; }

As you can see, I am applying the same gradient four times and each one has a different position to cover only one side at a time.

Another one? Let’s go!

CodePen Embed Fallback

This one looks a bit tricky and it indeed does require some imagination to understand how two conic gradients are pulling off this kind of magic. Here is a demo to illustrate one of the gradients:

CodePen Embed Fallback

The pseudo-element simulates the gradient. It’s initially out of sight and, on hover, we first change its position to get the top edge of the frame. Then we increase the height to get the right edge. The gradient shape is similar to the ones we used in the last section: two segments to cover two sides.

But why did I make the gradient’s width 200%? You’d think 100% would be enough, right?

100% should be enough but I won’t be able to move the gradient like I want if I keep its width equal to 100%. That’s another little quirk related to how background-position works. I cover this in a previous article. I also posted an answer over at Stack Overflow dealing with this. I know it’s a lot of reading, but it’s really worth your time.

Now that we have explained the logic for one gradient, the second one is easy because it’s doing exactly the same thing, but covering the left and bottom edges instead. All we have to do is to swap a few values and we are done:

img { --c: #8A9B0F; /* the border color */ --b: 10px; /* the border thickness*/ --g: 5px; /* the gap */ padding: calc(var(--g) + var(--b)); --_g: #0000 25%, var(--c) 0; background: conic-gradient(from 180deg at top var(--b) right var(--b), var(--_g)) var(--_i, 200%) 0 / 200% var(--_i, var(--b)) no-repeat, conic-gradient( at bottom var(--b) left var(--b), var(--_g)) 0 var(--_i, 200%) / var(--_i, var(--b)) 200% no-repeat; transition: .3s, background-position .3s .3s; cursor: pointer; } img:hover { --_i: 100%; transition: .3s, background-size .3s .3s; }

As you can see, both gradients are almost identical. I am simply swapping the values of the size and position.

The Frame Rotation

This time we are not going to draw a frame around our image, but rather adjust the look of an existing one.

CodePen Embed Fallback

You are probably asking how the heck I am able to transform a straight line into an angled line. No, the magic is different than that. That’s just the illusion we get after combining simple animations for four gradients.

Let’s see how the animation for the top gradient is made:

CodePen Embed Fallback

I am simply updating the position of a repeating gradient. Nothing fancy yet! Let’s do the same for the right side:

CodePen Embed Fallback

Are you starting to see the trick? Both gradients intersect at the corner to create the illusion where the straight line is changed to an angled one. Let’s remove the outline and hide the overflow to better see it:

CodePen Embed Fallback

Now, we add two more gradients to cover the remaining edges and we are done:

img { --g: 4px; /* the gap */ --b: 12px; /* border thickness*/ --c: #669706; /* the color */ padding: calc(var(--g) + var(--b)); --_c: #0000 0 25%, var(--c) 0 50%; --_g1: repeating-linear-gradient(90deg ,var(--_c)) repeat-x; --_g2: repeating-linear-gradient(180deg,var(--_c)) repeat-y; background: var(--_g1) var(--_p, 25%) 0, var(--_g2) 0 var(--_p, 125%), var(--_g1) var(--_p, 125%) 100%, var(--_g2) 100% var(--_p, 25%); background-size: 200% var(--b), var(--b) 200%; transition: .3s; } img:hover { --_p: 75%; }

If we take this code and slightly adjust it, we can get another cool animation:

CodePen Embed Fallback

Can you figure out the logic in this example? That’s your homework! The code may look scary but it uses the same logic as the previous examples we looked at. Try to isolate each gradient and imagine how it animates.

Wrapping up

That’s a lot of gradients in one article!

It sure is and I warned you! But if the challenge is to decorate an image without an extra elements and pseudo-elements, we are left with only a few possibilities and gradients are the most powerful option.

Don’t worry if you are a bit lost in some of the explanations. I always recommend some of my old articles where I go into greater detail with some of the concepts we recycled for this challenge.

I am gonna leave with one last demo to hold you over until the next article in this series. This time, I am using radial-gradient() to create another funny hover effect. I’ll let you dissect the code to grok how it works. Ask me questions in the comments if you get stuck!

CodePen Embed Fallback Fancy Image Decorations series

Fancy Image Decorations: Single Element Magic originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Some Things I Took Away From An Event Apart 2022 in Denver

Css Tricks - Thu, 10/13/2022 - 10:01am

An Event Apart 2022 Denver wrapped up yesterday. And while I was unable to make it to all three days this time, I did catch yesterday’s action — and it was awesome. I’m not very social or outgoing, but this was the first conference I’ve been to in at least a couple of years, and seeing folks in person was incredibly refreshing.

I took notes, of course! I thought I’d post ’em here because sharing is caring. At least, that’s what my six-year-old told me the other day when asking for a bite of my dessert last night.

I’ll break this down by speaker. Fair warning: I’m all about handwritten notes and a pretty visual fella, so my notes tend to be less… structured than most. And these notes are just things that stood out to me. They may not even be the presenter’s main idea, but they caught my attention!

Chris Coyier: Websites Are Good Now High-resolution

Chris has given this talk before (we linked it up just last week), but this time expanded it substantially, particularly with details on container relative units which, when combined with clamp(), make for more accurate responsiveness because the values are relative to the container rather than the viewport. So, you know how we often use viewport width (vh) units for fluid type?

font-size: clamp(1rem, 1rem + 2vw, 2rem);

Well, we can use a container relative unit like container query inline-size (cqi) instead, where 1cqi is equal to 1% of the container’s inline size (here’s the draft spec on that):

font-size: clamp(1rem, 1rem + 1cqi, 2rem);

Chris also talked quite a bit about the performance benefits of hosting at the edge. Probably no surprise because he’s written about it here more than a few times. Even as someone who had already read those articles, I honestly didn’t realize the complete concept of computing at the edge.

The idea is deceptively simple: global CDNs can serve assets quickly because they host them geographically close to the user. That’s pretty standard practice for serving raster images. But it has extended to static files, such as the same HTML, CSS, and JavaScript files that power a site — build them in advance and serve the already compiled and optimized files from the speedy global CDN. That’s the whole Jamstack concept!

But what if you still require a server response from it? That ain’t very edge-y, is it? Well, now we have handlers capable of running on a single URL fetching data in advance, and injecting it ahead of render — directly from the CDN. Sure, there’s extra work happening in the background. Still, the fact that we can dynamically fetch data, inject it, pre-build it, serve it statically on demand, and have it run geographically closer to the user makes this blazingly fast.

Tolu Adegbite: How to Win at ARIA and Influence Web Accessibility High resolution

Good gosh was this an excellent presentation! Tolu Adegbite schooled me so hard on WAI-ARIA that I had a hard time jotting down all the gems she shared — Roles! States! Labeling! Descriptions! Everything was extraordinarily well-covered, and stuff that I know I’ll be coming back to time and again.

But one specific thing that caught my attention is the accessibility of inline SVG. Even though SVG is related to other types of design assets, the fact that it is markup at the end of the day sets it apart because it isn’t always identified as an image.

<!-- Image tag is easily recognized as an image --> <img src="cat.svg" alt="An illustrated brown and white tabby kitten looking lovingly into the camera."> <!-- Could be an image, maybe not? --> <svg viewBox="0 0 100 100"> <!-- etc. --> </svg>

Assistive tech is more likely to read inline SVG as an image by giving it a proper accessible role and label:

<svg role="image" aria-label="An illustrated brown and white tabby kitten looking lovingly into the camera." viewBox="0 0 100 100" > <!-- etc. --> </svg> Miriam Suzanne: Cascading Layers of !mportance High resolution

Hey, another CSS-Tricks alum! Miriam has been spending a bunch of time and effort on the Cascade Layers specification. She also wrote a big ol’ guide about them here at CSS-Tricks and talked about them at An Event Apart.

What has stuck with me most is how big of a mental shift this is. The concept isn’t complicated, per se. Declare @layer at the top of the CSS document, list the layers in order of specificity, then write styles in those layers. But for an old dinosaur like me who has been writing CSS for a while, I’m going to have to get used to the fact that Cascade Layers make it possible for a simple class selector to beat out something that usually wields a higher specificity, like an ID.

CodePen Embed Fallback


Miriam also reminded the room that Cascade Layers are just one tool we have in our specificity-managing toolbelt, in addition to selectors that affect specificity (e.g., :is(), :where(), and :has()).

Oh, and this is an interesting tidbit. As Miriam walked through the history of specificity in CSS, she recalled that !important was initially designed as a tool for users to override user agent and author styles. But somewhere down the line, we’ve adopted it to force author styles to the top. Cascade Layers help remove the excuse need to use !important because they provide us the power to “prioritize layers and protect inheritance.”

That is beautifully said, Miriam!

Dave Rupert: Unblocking Your Accessibility Backlog High resolution

Imagine waking up one day to hundreds of GitHub notifications about reported issues on your site. Where do you even begin? Maybe close your laptop and get a root canal instead? That happened to Dave! An automated accessibility audit returned a massive pile of errors and assigned them as tickets for Dave to fix.

But he noticed a pattern after taking an Excel spreadsheet of those issues, moving them to Notion for a better view, hiding unnecessary columns, categorizing everything, and displaying the results in logical groups. Many of the reported issues were the same issue repeated on multiple pages. Just because an automated test returns a handful of errors doesn’t mean they’re all unique. That reduced a nice chunk of the tickets.

He went on to show how — with relatively little effort — the backlog of issues dwindled by nearly 50%.

There’s a lot to glean there, especially regarding how we process and organize our work. The biggest takeaway for me is when Dave said we have to emphasize individuals and interactions over processes and tools. Tools like the one scanning for accessibility errors are helpful, but they might not tell the entire story. Rather than take them at their words, it’s worth asking questions and gaining more context before diving into the mess.

As a bonus, reorganizing the issues in Notion allowed Dave to group issues in a way that clearly shows which impairments his product was actively discriminating against, giving him greater empathy for those misses and how to prioritize them.

One more virtual session by Hui Jing Chen capped the day, but admittedly, I missed about half of it because I was having a hallway conversation. The conversation was worth it, even though I am bummed I missed the presentation. I’ll be watching the video of it when it’s published!

Some Things I Took Away From An Event Apart 2022 in Denver originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

A Pure CSS Gallery Focus Effect with :not

Css Tricks - Thu, 10/13/2022 - 5:10am

Oftentimes in the past, I needed to figure out how to add styles to all elements inside the container but not the hovered one.

Demo of the expected “fade-out” effect on siblings to let users “focus” on a particular element.

This effect requires selecting the siblings of a hovered element. I used to apply JavaScript for this, adding or removing the class that defined the proper CSS rules on mouseenter and mouseleave events, similar to this:

CodePen Embed Fallback

Although the code does the trick, my gut feeling always told me that there must be some pure-CSS way to achieve the same result. A few years ago, while working on a certain slider for my company, I came up with a solution similar to how Chris Geelhoed recreated the famous Netflix homepage animation and I understood that I didn’t need JavaScript for this anymore.

A couple of months ago I was trying to implement the same approach to a grid-based feed on my company website and — boom — it didn’t work because of the gap between the elements!

Luckily for me, it appeared that it doesn’t have to stay like this, and once again I didn’t need JavaScript for it.

Markup and base CSS

Let’s start coding by preparing the proper markup:

  • .grid is a grid-based <ul> list;
  • and .grid__child elements are <li> children that we want to interact with.

The markup looks like this:

<ul class="grid"> <li class="grid__child"></li> <li class="grid__child"></li> <li class="grid__child"></li> </ul>

The style should look like this:

.grid { display: grid; grid-template-columns: repeat(auto-fit, 15rem); grid-gap: 1rem; } .grid__child { background: rgba(0, 0, 0, .1); border-radius: .5rem; aspect-ratio: 1/1; }

This example code will create three list items occupying three columns in a grid.

The power of CSS selectors

Now, let’s add some interactivity. The approach that I initially applied was based on two steps:

  1. hovering on the container should change the styles of all elements inside…  
  2. …except the one that cursor is hovering at the moment.

Let’s start with grabbing every child while the cursor is hovering over the container:

.grid:hover .grid__child { /* ... */ }

Secondly, let’s exclude the currently hovered item and reduce the opacity of any other child:

.grid:hover .grid__child:not(:hover) { opacity: 0.3; }

And this would be perfectly enough for containers without gaps between the child elements:

Demo of a solution that works without gaps.

However, in my case, I couldn’t remove these gaps:

Demo of the problem encountered when gaps are introduced.

When I was moving the mouse between the tiles all of the children elements were fading out.

Ignoring the gaps

We can assume that gaps are parts of the container that are not overlayed by its children. We don’t want to run the effect every time the cursor enters the container, but rather when it hovers over one of the elements inside. Can we ignore the cursor moving above the gaps then? 

Yes, we can, using pointer-events: none on the .grid container and bringing them back with pointer-events: auto on its children:

.grid { /* ... */ pointer-events: none; } /* ... */ .grid__child { /* ... */ pointer-events: auto; }

Let’s just add some cool transition on opacity and we have a ready component:

CodePen Embed Fallback

It’s probably even cooler when we add more tiles and create a 2-dimensional layout:

CodePen Embed Fallback

The final CSS looks like this:

.grid { display: grid; grid-template-columns: repeat(auto-fit, 15rem); grid-gap: 3rem; pointer-events: none; } .grid:hover .grid__child:not(:hover) { opacity: 0.3; } .grid__child { background: rgba(0, 0, 0, .1); border-radius: .5rem; aspect-ratio: 1/1; pointer-events: auto; transition: opacity 300ms; }

With only 2 additional lines of code we overcame the gap problem!

Possible issues

Although it’s a compact solution, there are some situations where it might require some workarounds.

Unfortunately, this trick won’t work when you want the container to be scrollable, e.g., like in some kind of horizontal slider. The pointer-events: none style would ignore not only the hover event but all the others, too. In such situations, you can wrap the .grid in another container, like this:

<div class="container"> <ul class="grid"> <li class="grid__child"></li> <li class="grid__child"></li> <li class="grid__child"></li> <li class="grid__child"></li> <li class="grid__child"></li> <li class="grid__child"></li> <li class="grid__child"></li> </ul> </div> Summary

I strongly encourage you to experiment and try to find a simpler and more native approach for tasks that are usually expected to have some level of complexity. Web technologies, like CSS, are getting more and more powerful and by using out-of-the-box native solutions you can achieve great results without the need of maintaining your code and cede it to browser vendors.

I hope that you liked this short tutorial and found it useful. Thanks!

The author selected the Tech Education to receive a donation as part of the Write for DOnations program.

A Pure CSS Gallery Focus Effect with :not originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Early Days of Container Style Queries

Css Tricks - Wed, 10/12/2022 - 3:06am

We’re still in suuuuuper early days with container queries. Too early for broad browser support, but Chromium already supports it, Safari started supporting it in version 16, and Firefox is presumably not far behind.

Most early days conversations revolving around container queries usually compare the syntax to media queries.

/* Stacked flex container */ .post { display: flex; flex-direction: column; } /* Change direction when viewport is 600px or wider */ @media(min-width: 600px) { .post { flex-direction: row; } }

/* Define the container */ .posts { container-name: posts; container-type: inline-size; } .post { display: flex; flex-direction: column; } /* Query the container's min-width */ @container posts (min-width: 600px) { /* Change styles when `posts` container is 600px or wider */ .post { flex-direction: row; } }

Both of these are making queries for min-width: 600. The difference is that the media query is looking at the viewport’s width to trigger those style changes while the container query is looking at the computed width of the .posts element. Sweet!

But after listening to CSS Podcast Episode 59, Una and Adam poked at the future of container queries: style queries! The current working draft of the CSS Containment Module Level 3 spec defines container style queries:

A container style query allows querying the computed values of the query container. It is a boolean combination of individual style features (<style-feature>) that each query a single, specific property of the query container.

But no examples on syntax just yet — only a brief description:

The syntax of a <style-feature> is the same as for a declaration, and its query is true if the computed value of the given property on the query container matches the given value (which is also computed with respect to the query container), unknown if the property or its value is invalid or unsupported, and false otherwise. The boolean syntax and logic combining style features into a style query is the same as for CSS feature queries. (See @supports.)

So, yes, given time we should expect to pull off something like this:

.posts { container-name: posts; } @container posts (background-color: #f8a100) { /* Change styles when `posts` container has an orange background */ .post { color: #fff; } }

That’s a pretty dumb example. One thing to note is that the container-type is no longer based on the container’s inline-size but by style. We could delcare that like so:

.posts { container-name: posts; container-type: style; /* unnecessary */ }

…but all container queries are style queries by default. Well. at least as it stands today. Miriam Suzanne has a nice outline of the possible issues that might pop up with that.

Where might querying a container’s styles come in handy? I don’t know yet! But my mind gos to a few places:

  • Custom property values: We’ve seen custom properties used like state indicators, such as the DRY-switching method Ana covered a while back. The value changes, and so do styles.
  • Alternate dark mode approach: Instead of basing it all on a body class change that re-assigns custom property values, maybe we can change an entire color palette if, say, the body background changes color.
  • More complex query conditions: Like, say, we want to apply styles when the size and style conditions for a container are met.

Una also mentioned in the CSS Podcast that container style queries could help prevent some awkward styling situations, like if we happen to have italicized text in an already italicized blockquote:

blockquote { container-name: quote; } @container quote (font-style: italic) { em, i, q, address { font-style: normal; } }

Early Days of Container Style Queries originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Rendering External API Data in WordPress Blocks on the Front End

Css Tricks - Tue, 10/11/2022 - 6:15am

There’ve been some new tutorials popping here on CSS-Tricks for working with WordPress blocks. One of them is an introduction to WordPress block development and it’s a good place to learn what blocks are and to register them in WordPress for use in pages and posts.

While the block basics are nicely covered in that post, I want to take it another step forward. You see, in that article, we learned the difference between rendering blocks in the back-end WordPress Block Editor and rendering them on the front-end theme. The example was a simple Pullquote Block that rendered different content and styles on each end.

Let’s go further and look at using dynamic content in a WordPress block. More specifically, let’s fetch data from an external API and render it on the front end when a particular block is dropped into the Block Editor.

We’re going to build a block that outputs data that shows soccer (er, football) rankings pulled from Api-Football.

This is what we’re working for together.

There’s more than one way to integrate an API with a WordPress block! Since the article on block basics has already walked through the process of making a block from scratch, we’re going to simplify things by using the @wordpress/create-block package to bootstrap our work and structure our project.

Initializing our block plugin

First things first: let’s spin up a new project from the command line:

npx @wordpress/create-block football-rankings

I normally would kick a project like this off by making the files from scratch, but kudos to the WordPress Core team for this handy utility!

Once the project folder has been created by the command, we technically have a fully-functional WordPress block registered as a plugin. So, let’s go ahead and drop the project folder into the wp-content/plugins directory where you have WordPress installed (probably best to be working in a local environment), then log into the WordPress admin and activate it from the Plugins screen.

Now that our block is initialized, installed, and activated, go ahead and open up the project folder from at /wp-content/plugins/football-rankings. You’re going to want to cd there from the command line as well to make sure we can continue development.

These are the only files we need to concentrate on at the moment:

  • edit.js
  • index.js
  • football-rankings.php

The other files in the project are important, of course, but are inessential at this point.

Reviewing the API source

We already know that we’re using Api-Football which comes to us courtesy of RapidAPI. Fortunately, RapidAPI has a dashboard that automatically generates the required scripts we need to fetch the API data for the 2021 Premier League Standings.

The RapidAPI dashboard

If you want to have a look on the JSON structure, you can generate visual representation with JSONCrack.

Fetching data from the edit.js file

I am going to wrap the RapidAPI code inside a React useEffect() hook with an empty dependency array so that it runs only once when the page is loaded. This way, we prevent WordPress from calling the API each time the Block Editor re-renders. You can check that using wp.data.subscribe() if you care to.

Here’s the code where I am importing useEffect(), then wrapping it around the fetch() code that RapidAPI provided:

/** * The edit function describes the structure of your block in the context of the * editor. This represents what the editor will render when the block is used. * * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit * * @return {WPElement} Element to render. */ import { useEffect } from "@wordpress/element"; export default function Edit(props) { const { attributes, setAttributes } = props; useEffect(() => { const options = { method: "GET", headers: { "X-RapidAPI-Key": "Your Rapid API key", "X-RapidAPI-Host": "api-football-v1.p.rapidapi.com", }, }; fetch("https://api-football-v1.p.rapidapi.com/v3/standings?season=2021&league=39", options) .then( ( response ) => response.json() ) .then( ( response ) => { let newData = { ...response }; setAttributes( { data: newData } ); console.log( "Attributes", attributes ); }) .catch((err) => console.error(err)); }, []); return ( <p { ...useBlockProps() }> { __( "Standings loaded on the front end", "external-api-gutenberg" ) } </p> ); }

Notice that I have left the return function pretty much intact, but have included a note that confirms the football standings are rendered on the front end. Again, we’re only going to focus on the front end in this article — we could render the data in the Block Editor as well, but we’ll leave that for another article to keep things focused.

Storing API data in WordPress

Now that we are fetching data, we need to store it somewhere in WordPress. This is where the attributes.data object comes in handy. We are defining the data.type as an object since the data is fetched and formatted as JSON. Make sure you don’t have any other type or else WordPress won’t save the data, nor does it throw any error for you to debug.

We define all this in our index.js file:

registerBlockType( metadata.name, { edit: Edit, attributes: { data: { type: "object", }, }, save, } );

OK, so WordPress now knows that the RapidAPI data we’re fetching is an object. If we open a new post draft in the WordPress Block Editor and save the post, the data is now stored in the database. In fact, if we can see it in the wp_posts.post_content field if we open the site’s database in phpMyAdmin, Sequel Pro, Adminer, or whatever tool you use.

API output stored in the WordPress database Outputting JSON data in the front end

There are multiple ways to output the data on the front end. The way I’m going to show you takes the attributes that are stored in the database and passes them as a parameter through the render_callback function in our football-rankings.php file.

I like keeping a separation of concerns, so how I do this is to add two new files to the block plugin’s build folder: frontend.js and frontend.css (you can create a frontend.scss file in the src directory which compiled to CSS in the build directory). This way, the back-end and front-end codes are separate and the football-rankings.php file is a little easier to read.

Referring back to the introduction to WordPress block development, there are editor.css and style.css files for back-end and shared styles between the front and back end, respectively. By adding frontend.scss (which compiles to frontend.css, I can isolate styles that are only intended for the front end.

Before we worry about those new files, here’s how we call them in football-rankings.php:

/** * Registers the block using the metadata loaded from the `block.json` file. * Behind the scenes, it registers also all assets so they can be enqueued * through the block editor in the corresponding context. * * @see https://developer.wordpress.org/reference/functions/register_block_type/ */ function create_block_football_rankings_block_init() { register_block_type( __DIR__ . '/build', array( 'render_callback' => 'render_frontend' )); } add_action( 'init', 'create_block_football_rankings_block_init' ); function render_frontend($attributes) { if( !is_admin() ) { wp_enqueue_script( 'football_rankings', plugin_dir_url( __FILE__ ) . '/build/frontend.js'); wp_enqueue_style( 'football_rankings', plugin_dir_url( __FILE__ ) . '/build/frontend.css' ); // HIGHLIGHT 15,16,17,18 } ob_start(); ?> <div class="football-rankings-frontend" id="league-standings"> <div class="data"> <pre> <?php echo wp_json_encode( $attributes ) ?> </pre> </div> <div class="header"> <div class="position">Rank</div> <div class="team-logo">Logo</div> <div class="team-name">Team name</div> <div class="stats"> <div class="games-played">GP</div> <div class="games-won">GW</div> <div class="games-drawn">GD</div> <div class="games-lost">GL</div> <div class="goals-for">GF</div> <div class="goals-against">GA</div> <div class="points">Pts</div> </div> <div class="form-history">Last 5 games</div> </div> <div class="league-table"></div> </div> <?php return ob_get_clean(); }

Since I am using the render_callback() method for the attributes, I am going to handle the enqueue manually just like the Block Editor Handbook suggests. That’s contained in the !is_admin() condition, and is enqueueing the two files so that we avoid enqueuing them while using the editor screen.

Now that we have two new files we’re calling, we’ve gotta make sure we are telling npm to compile them. So, do that in package.json, in the scripts section:

"scripts": { "build": "wp-scripts build src/index.js src/frontend.js", "format": "wp-scripts format", "lint:css": "wp-scripts lint-style", "lint:js": "wp-scripts lint-js", "packages-update": "wp-scripts packages-update", "plugin-zip": "wp-scripts plugin-zip", "start": "wp-scripts start src/index.js src/frontend.js" },

Another way to include the files is to define them in the block metadata contained in our block.json file, as noted in the introduction to block development:

"viewScript": [ "file:./frontend.js", "example-shared-view-script" ], "style": [ "file:./frontend.css", "example-shared-style" ],

The only reason I’m going with the package.json method is because I am already making use of the render_callback() method.

Rendering the JSON data

In the rendering part, I am concentrating only on a single block. Generally speaking, you would want to target multiple blocks on the front end. In that case, you need to make use of document.querySelectorAll() with the block’s specific ID.

I’m basically going to wait for the window to load and grab data for a few key objects from JSON and apply them to some markup that renders them on the front end. I am also going to convert the attributes data to a JSON object so that it is easier to read through the JavaScript and set the details from JSON to HTML for things like the football league logo, team logos, and stats.

The “Last 5 games” column shows the result of a team’s last five matches. I have to manually alter the data for it since the API data is in a string format. Converting it to an array can help make use of it in HTML as a separate element for each of a team’s last five matches.

import "./frontend.scss"; // Wait for the window to load window.addEventListener( "load", () => { // The code output const dataEl = document.querySelector( ".data pre" ).innerHTML; // The parent rankings element const tableEl = document.querySelector( ".league-table" ); // The table headers const tableHeaderEl = document.querySelector( "#league-standings .header" ); // Parse JSON for the code output const dataJSON = JSON.parse( dataEl ); // Print a little note in the console console.log( "Data from the front end", dataJSON ); // All the teams let teams = dataJSON.data.response[ 0 ].league.standings[ 0 ]; // The league logo let leagueLogoURL = dataJSON.data.response[ 0 ].league.logo; // Apply the league logo as a background image inline style tableHeaderEl.style.backgroundImage = `url( ${ leagueLogoURL } )`; // Loop through the teams teams.forEach( ( team, index ) => { // Make a div for each team const teamDiv = document.createElement( "div" ); // Set up the columns for match results const { played, win, draw, lose, goals } = team.all; // Add a class to the parent rankings element teamDiv.classList.add( "team" ); // Insert the following markup and data in the parent element teamDiv.innerHTML = ` <div class="position"> ${ index + 1 } </div> <div class="team-logo"> <img src="${ team.team.logo }" /> </div> <div class="team-name">${ team.team.name }</div> <div class="stats"> <div class="games-played">${ played }</div> <div class="games-won">${ win }</div> <div class="games-drawn">${ draw }</div> <div class="games-lost">${ lose }</div> <div class="goals-for">${ goals.for }</div> <div class="goals-against">${ goals.against }</div> <div class="points">${ team.points }</div> </div> <div class="form-history"></div> `; // Stringify the last five match results for a team const form = team.form.split( "" ); // Loop through the match results form.forEach( ( result ) => { // Make a div for each result const resultEl = document.createElement( "div" ); // Add a class to the div resultEl.classList.add( "result" ); // Evaluate the results resultEl.innerText = result; // If the result a win if ( result === "W" ) { resultEl.classList.add( "win" ); // If the result is a draw } else if ( result === "D" ) { resultEl.classList.add( "draw" ); // If the result is a loss } else { resultEl.classList.add( "lost" ); } // Append the results to the column teamDiv.querySelector( ".form-history" ).append( resultEl ); }); tableEl.append( teamDiv ); }); });

As far as styling goes, you’re free to do whatever you want! If you want something to work with, I have a full set of styles you can use as a starting point.

I styled things in SCSS since the @wordpress/create-block package supports it out of the box. Run npm run start in the command line to watch the SCSS files and compile them to CSS on save. Alternately, you can use npm run build on each save to compile the SCSS and build the rest of the plugin bundle.

View SCSS body { background: linear-gradient(to right, #8f94fb, #4e54c8); } .data pre { display: none; } .header { display: grid; gap: 1em; padding: 10px; grid-template-columns: 1fr 1fr 3fr 4fr 3fr; align-items: center; color: white; font-size: 16px; font-weight: 600; background-repeat: no-repeat; background-size: contain; background-position: right; } .frontend#league-standings { width: 900px; margin: 60px 0; max-width: unset; font-size: 16px; .header { .stats { display: flex; gap: 15px; &amp; &gt; div { width: 30px; } } } } .league-table { background: white; box-shadow: rgba(50, 50, 93, 0.25) 0px 2px 5px -1px, rgba(0, 0, 0, 0.3) 0px 1px 3px -1px; padding: 1em; .position { width: 20px; } .team { display: grid; gap: 1em; padding: 10px 0; grid-template-columns: 1fr 1fr 3fr 4fr 3fr; align-items: center; } .team:not(:last-child) { border-bottom: 1px solid lightgray; } .team-logo img { width: 30px; } .stats { display: flex; gap: 15px; } .stats &gt; div { width: 30px; text-align: center; } .form-history { display: flex; gap: 5px; } .form-history &gt; div { width: 25px; height: 25px; text-align: center; border-radius: 3px; font-size: 15px; } .form-history .win { background: #347d39; color: white; } .form-history .draw { background: gray; color: white; } .form-history .lost { background: lightcoral; color: white; } } Here’s the demo!

Check that out — we just made a block plugin that fetches data and renders it on the front end of a WordPress site.

Open demo

We found an API, fetch()-ed data from it, saved it to the WordPress database, parsed it, and applied it to some HTML markup to display on the front end. Not bad for a single tutorial, right?

Again, we can do the same sort of thing so that the rankings render in the Block Editor in addition to the theme’s front end. But hopefully keeping this focused on the front end shows you how fetching data works in a WordPress block, and how the data can be structured and rendered for display.

Rendering External API Data in WordPress Blocks on the Front End originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Adding Fluid Typography Support to WordPress Block Themes

Css Tricks - Fri, 10/07/2022 - 3:19am

Fluid typography is a fancy way of “describing font properties, such as size or line height, that scale fluidly according to the size of the viewport”. It’s also known by other names, like responsive typography, flexible type, fluid type, viewport sized typography, fluid typography, and even responsive display text.

Here is an example of fluid typography that you can play live (courtesy of MDN documentation). CSS-Tricks has covered fluid typography extensively as well. But the point here is not to introduce you to fluid typography, but how to use it. More specifically, I want to show you how to implement fluid typography in WordPress 6.1 which recently introduced a fluid type feature directly in the WordPress Block Editor.

Open up your style.css file, slap in a style rule with fancy clamp()-ing on the font-size property, and good to go, right? Sure, that’ll give you fluid text, but to get Block Editor controls that make it possible to apply fluid type anywhere on your WordPress site? That requires a different approach in these block-ified days.

Fluid typography support in Gutenberg

Some WordPress theme developers have been using the clamp() function to define a fluid font-size, in their WordPress themes, even in newer “block” themes such as Twenty Twenty-Two, Twenty Twenty-Three, and others.

But the Gutenberg plugin — the one that contains experimental development for WordPress Block and Site Editor features — introduced support for fluid typography starting in version 13.8. That opened the door for implementing at a theme level so that fluid type can be applied to specific elements and blocks directly in the Block Editor. CSS-Tricks was even given a shout-out in the Pull Request that merged the feature.

That work became part of WordPress Core in WordPress 6.1. Rich Tabor, one of the earlier advocates of fluid typography in the Block Editor says:

[Fluid typography] is also a part of making WordPress more powerful, while not more complicated (which we all know is quite the challenge). […] Fluid typography just works. Actually, I think it works great.

This Make WordPress post highlights the approach taken to support the feature at the block level so that a fluid font size is applied to blocks dynamically by default. There are some benefits to this, of course:

  • It provides a way for theme authors to activate fluid typography without worrying about implementing it in code.
  • It applies fluid typography to specific typographical entities, such as elements or blocks in a maintainable and reusable way.
  • It allows flexibility in terms of font size units (e.g. px, rem, em, and %).

Now that this new feature is available in the WordPress Block Editor by default, theme authors can apply uniform fluid typography without writing additional code.

Blocks that support typography and spacing settings

Gutenberg 14.1 released on September 16, 2022, and introduced typographic settings on a bunch of blocks. That means the text settings for those blocks were set in CSS before and had to be changed in CSS as well. But those blocks now provide font and spacing controls in the Block Editor interface.

That work is currently slated to be added to WordPress 6.1, as detailed in this Make WordPress blog post. And with it is an expanded number of blocks that with typography support.

WordPress blocks that will support typography settings in the upcoming WordPress 6.1 release. Declaring fluid type in a WordPress block theme

So, how do we put this new fluid typography to use in WordPress? The answer is in theme.json, a new-ish file specific to block themes that contains a bunch of theme configurations in key:value pairs.

Let’s look at a rule for a large font in theme.json where contentSize: 768px and we’re working with a widesize: 1600px layout. This is how we can specify a CSS font-size using the clamp() function:

"settings": { "appearanceTools": true, "layout": { "contentSize": "768px", "wideSize": "1600px" }, "typography": { "fontSizes": [ { "name": "Large", "size": "clamp(2.25rem, 6vw, 3rem)", "slug": "large" } ] } }

As of WordPress 6.1, only rem, em and px units are supported.

That’s great and works, but with the new fluid type feature we would actually use a different approach. First, we opt into fluid typography on settings.typography, which has a new fluid property:

"settings": { "typography": { "fluid": true } }

Then we specify our settings.fontSizes like before, but with a new fluidSize property where we can set the min and max size values for our fluid type range.

"settings": { "appearanceTools": true, "layout": { "contentSize": "768px", "wideSize": "1600px" }, "typography": { "fontSizes": [ { "size": "2.25rem", "fluidSize": { "min": "2.25rem", "max": "3rem" }, "slug": "large", "name": "Large" } ] } }

That’s really it. We just added fluid type to a font size called “Large” with a range that starts at 2.25rem and scales up to 3rem. Now, we can apply the “Large” font to any block with font settings.

How does this works under the hood? Rich Tabor offers a nice explanation, as does this Pull Request in GitHub. In short, WordPress converts the theme.json properties into the following CSS rule:

.has-large-font-size { font-size: clamp(36px, calc(2.25rem + ((1vw - 7.68px) * 1.4423)), 48px); }

…which is applied to the element, say a Paragraph Block:

<p class="has-large-font-size">...</p>

Initially, I found it hard to understand and wrap around in my mind the concept of the CSS clamp() function without also learning about the min(), max(), and calc() functions. This calculator tool helped me quite a bit, especially for determining which values to use in my own theme projects.

For demonstration purposes, let’s use the calculator to define our font-size range so that the size is 36px at a 768px viewport width and 48px at a 1600px viewport width.

The calculator automatically generates the following CSS:

/* 36px @ 768px increasing to 48px @ 1600px */ font-size: clamp(36px, calc(2.25rem + ((1vw - 7.68px) * 1.4423)), 48px);

The calculator provide options to select input units as px, rem, and em. If we select rem unit, the calculator generates the following clamp() value:

/* 2.25rem @ 48rem increasing to 3rem @ 100rem */ font-size: clamp(2.25rem, calc(2.25rem + ((1vw - 0.48rem) * 1.4423)), 3rem);

So, those minimum and maximum values correspond to the the fluidSize.min and fluidSize.max values in theme.json. The min value is applied at viewports that are 768px wide and below. Then the font-size scales up as the viewport width grows. If the viewport is wider than 1600px, the max is applied and the font-size is capped there.


There are detailed testing instructions in the merged Pull Request that introduced the feature. There are even more testing instructions from Justin Tadlock’s pre-prelease post on Make WordPress.

Example 1: Setting a new fluid font setting

Let’s start with Justin’s set of instructions. I used in a modified version of the default Twenty Twenty-Three theme that is currently under development.

First, let’s make sure we’re running the Gutenberg plugin (13.8 and up) or WordPress 6.1, then opt into fluid type on the settings.typography.fluid property in the theme.json file:

{ "version": 2, "settings": { "appearanceTools": true, "layout": { "contentSize": "768px", "wideSize": "1600px" }, "typography": { "fluid": true } } }

Now, let’s drop the settings.typography.fontSizes examples in there:

{ "version": 2, "settings": { "appearanceTools": true, "layout": { "contentSize": "768px", "wideSize": "1600px" }, "typography": { "fluid": true "fontSizes": [ { "name": "Normal", "size": "1.125rem", "fluid": { "min": "1rem", "max": "1.5rem" }, "slug": "normal" } ] } } }

If everything is working correctly, we can now head into the WordPress Block Editor and apply the “Normal” font setting to our block:

Nice! And if we save and inspect that element on the front end, this is the markup:

Very good. Now let’s make sure the CSS is actually there:

Good, good. Let’s expose that CSS custom property to see if it’s really clampin’ things:

Looks like everything is working just as we want it! Let’s look at another example…

Example 2: Excluding a font setting from fluid type

This time, let’s follow the instructions from the merged Pull Request with a nod to this example by Carolina Nymark that shows how we can disable fluid type on a specific font setting.

I used the empty theme as advised in the instructions and opened up the theme.json file for testing. First, we opt into fluid type exactly as we did before:

{ "version": 2, "settings": { "appearanceTools": true, "layout": { "contentSize": "768px", "wideSize": "1000px" }, "typography": { "fluid": true } } }

This time, we’re working with smaller wideSize value of 1000px instead of 1600px. This should allow us to see fluid type working in an exact range.

OK, on to defining some custom font sizes under settings.typography.fontSizes:

{ "version": 2, "settings": { "typography": { "fluid": true, "fontSizes": [ { "size": ".875rem", "fluid": { "min": "0.875rem", "max": "1rem" }, "slug": "small", "name": "Small" }, { "size": "1rem", "fluid": { "min": "1rem", "max": "1.5rem" }, "slug": "normal", "name": "Normal" }, { "size": "1.5rem", "fluid": { "min": "1.5rem", "max": "2rem" }, "slug": "large", "name": "Large" }, { "size": "2.25rem", "fluid": false, "slug": "x-large", "name": "Extra large" } ] } } }

Notice that we’ve applied the fluid type feature only on the “Normal”, “Medium”, and “Large” font settings. “Extra Large” is the odd one out where the fluid object is set to false.

What WordPress does from here — via the Gutenberg style engine — is apply the properties we set into CSS clamp() functions for each font size setting that has opted into fluid type and a single size value for the Extra Large setting:

--wp--preset--font-size--small: clamp(0.875rem, 0.875rem + ((1vw - 0.48rem) * 0.24), 1rem); --wp--preset--font-size--medium: clamp(1rem, 1rem + ((1vw - 0.48rem) * 0.962), 1.5rem); --wp--preset--font-size--large: clamp(1.5rem, 1.5rem + ((1vw - 0.48rem) * 0.962), 2rem); --wp--preset--font-size--x-large: 2.25rem;

Let’s check the markup on the front end:

Good start! Let’s confirm that the .has-x-large-font-size class is excluded from fluid type:

If we expose the --wp--preset--font-size--x-large variable, we’ll see it’s set to 2.25rem.

That’s exactly what we want!

Block themes that support fluid typography

Many WordPress themes already make use of the clamp() function for fluid type in both block and classic themes. A good example of fluid typography use is the recently released Twenty Twenty-Three default theme.

I’ve reviewed all the block themes from WordPress Block Theme directory, examining theme.json file of each theme and to see just how many block themes currently support fluid typography — not the new feature since it’s still in the Gutenberg plugin as of this writing — using the CSS clamp() function. Of the 146 themes I reviewed, the majority of them used a clamp() function to define spacing. A little more than half of them used clamp() to define font sizes. The Alara theme is the only one to use clamp() for defining the layout container sizes.

Understandably, only a few recently released themes contain the new fluid typography feature. But here are the ones I found that define it in theme.json:

And if you read my previous post here on CSS-Tricks, the TT2 Gopher Blocks theme I used for the demo has also been updated to support the fluid typography feature.

Selected reactions to the WordPress fluid typography features

Having fluid typography in WordPress at the settings level is super exciting! I thought I’d share some thoughts from folks in the WordPress developer community who have commented on it.

Matias Ventura, the lead architect of the Gutenberg project:

One of my favorite latest Gutenberg features is fluid type that — hopefully — "just works". It's available for testing in 13.8. pic.twitter.com/9SLUgEg4pF

— Matías Ventura (@matias_ventura) August 4, 2022

Rich Tabor:

As one of the bigger efforts towards making publishing beautifully rich pages in WordPress, fluid typography is a pretty big experience win for both the folks building with WordPress — and those consuming the content.

Automattic developer Ramon Dodd commented in the Pull Request:

Contrast that idea with font sizes that respond to specific viewport sizes, such as those defined by media queries, but do nothing in between those sizes. theme.json already allows authors to insert their own fluid font size values. This won’t change, but this PR offers it to folks who don’t want to worry about the implementation details.

Nick Croft, author of GenesisWP:

Not gonna lie, I think this is the feature I’m most excited about. Was using clamp to do this but the syntax looks easier for your average person.

— Nick Croft (@Nick_theGeek) September 1, 2022

Brian Garner, designer and principal developer advocate at WPEngine:

Fluid Typography is a huge improvement to #WordPress. FSE themes can experimentally opt into this via the Gutenberg plugin, but we’ll see it officially supported in 6.1 this fall. Here’s how it looks/works: pic.twitter.com/Jc7gHdyz5R

— Brian Gardner (@bgardner) September 1, 2022

A few developers think some features should be an opt-in. Jason Crist of Automattic says:

I love the power of fluid typography, however I also don’t believe that it should just be enabled by default. It’s usage (and the details of it) are important design decisions that should be made carefully.

You can also find a bunch more comments in the official testing instructions for the feature.

Wrapping up

The fluid typography feature in WordPress is still in active development at the time of this writing. So, right now, theme authors should proceed to use it, but with caution and expect some possible changes before it is officially released. Justin cautions theme authors using this feature and suggests to keep eye on the following two GitHub issues:

There is also still lots of ongoing work on typography and other design-related WordPress tools. If you’re interested, watch this typography tracking GitHub ticket and design tools related GitHub issues.


I used the following articles when researching fluid type and how WordPress is implementing it as a feature.

Tutorials and opinions CSS-Tricks calc() and related CSS functions

Adding Fluid Typography Support to WordPress Block Themes originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

How to Safely Share Your Email Address on a Website

Css Tricks - Thu, 10/06/2022 - 2:54am

Spammers are a huge deal nowadays. If you want to share your contact information without getting overwhelmed by spam email you need a solution. I run into this problem a few months ago. While I was researching how to solve it, I found different interesting solutions. Only one of them was perfect for my needs.

In this article, I am going to show you how to easily protect your email address from spam bots with multiple solutions. It’s up to you to decide what technique fits your needs.

Table of contents The traditional case

Let’s say that you have a website. You want to share your contact details, and you don’t want to share only your social links. The email address must be there. Easy, right? You type something like this:

<a href="mailto:email@address.com">Send me an Email</a>

And then you style it according to your tastes.

Well, even if this solution works, it has a problem. It makes your email address available to literally everyone, including website crawlers and all sorts of spam bots. This means that your inbox can be flooded with tons of unwanted rubbish like promotional offers or even some phishing campaign.

We are looking for a compromise. We want to make it hard for bots to get our email addresses, but as simple as possible for normal users.

The solution is obfuscation.

Obfuscation is the practice of making something difficult to understand. This strategy is used with source code for multiple reasons. One of them is hiding the purpose of the source code to make tampering or reverse-engineering more difficult. We will first look at different solutions that are all based on the idea of obfuscation.

The HTML approach

We can think of bots as software that browse the web and crawl through web pages. Once a bot obtains an HTML document, it interprets the content in it and extracts information. This extraction process is called web scraping. If a bot is looking for a pattern that matches the email format, we can try to disguise it by using a different format. For example, we could use HTML comments:

<p>If you want to get in touch, please drop me an email at<!-- fhetydagzzzgjds --> email@<!-- sdfjsdhfkjypcs -->addr<!-- asjoxp -->ess.com</p>

It looks messy, but the user will see the email address like this:

If you want to get in touch, please drop me an email at email@address.com


  • Easy to set up.
  • It works with JavaScript disabled.
  • It can be read by assistive technology.


  • Spam bots can skip known sequences like comments.
  • It doesn’t work with a mailto: link.
The HTML & CSS approach

What if we use the styling power of CSS to remove some content placed only to fool spam bots? Let’s say that we have the same content as before, but this time we place a span element inside:

<p>If you want to get in touch, please drop me an email at <span class="blockspam" aria-hidden="true">PLEASE GO AWAY!</span> email@<!-- sdfjsdhfkjypcs -->address.com</p>.

Then, we use the following CSS style rule:

span.blockspam { display: none; }

The final user will only see this:

If you want to get in touch, please drop me an email at email@address.com.

…which is the content we truly care about.


  • It works with JavaScript disabled.
  • It’s more difficult for bots to get the email address.
  • It can be read by assistive technology.


  • It doesn’t work with a mailto: link.
The JavaScript approach

In this example, we use JavaScript to make our email address unreadable. Then, when the page is loaded, JavaScript makes the email address readable again. This way, our users can get the email address.

The easiest solution uses the Base64 encoding algorithm to decode the email address. First, we need to encode the email address in Base64. We can use some websites like Base64Encode.org to do this. Type in your email address like this:

Then, click the button to encode. With these few lines of JavaScript we decode the email address and set the href attribute in the HTML link:

var encEmail = "ZW1haWxAYWRkcmVzcy5jb20="; const form = document.getElementById("contact"); form.setAttribute("href", "mailto:".concat(atob(encEmail)));

Then we have to make sure the email link includes id="contact" in the markup, like this:

<a id="contact" href="">Send me an Email</a>

We are using the atob method to decode a string of Base64-encoded data. An alternative is to use some basic encryption algorithm like the Caesar cipher, which is fairly straightforward to implement in JavaScript.


  • It’s more complicated for bots to get the email address, especially if you use an encryption algorithm.
  • It works with a mailto: link.
  • It can be read by assistive technology.


  • JavaScript must be enabled on the browser, otherwise, the link will be empty.
The embedded form approach

Contact forms are everywhere. You certainly have used one of them at least once. If you want a way for people to directly contact you, one of the possible solutions is implementing a contact form service on your website.

Formspree is one example of service which provides you all the benefits of a contact form without worrying about server-side code. Wufoo is too. In fact, here is a bunch you can consider for handling contact form submissions for you.

The first step to using any form service is to sign up and create an account. Pricing varies, of course, as do the features offered between services. But one thing most of them do is provide you with an HTML snippet to embed a form you create into any website or app. Here’s an example I pulled straight from a form I created in my Formspring account

<form action="https://formspree.io/f/[my-key]" method="POST"> <label> Your email: <input type="email" name="email" /> </label> <label> Your message: <textarea name="message"></textarea> </label> <!-- honeypot spam filtering --> <input type="text" name="_gotcha" style="display:none" /> <button type="submit">Send</button> </form>

In the first line, you should customize action based on your endpoint. This form quite basic, but you can add as many fields as you wish.

Notice the hidden input tag on line 9. This input tag helps you filter the submissions made by regular users and bots. In fact, if Formspree’s back-end sees a submission with that input filled, it will discard it. A regular user wouldn’t do that, so it must be a bot.


  • Your email address is safe since it is not public.
  • It works with Javascript disabled.


  • Relies on a third-party service (which may be a pro, depending on your needs)

There is one other disadvantage to this solution but I left it out of the list since it’s quite subjective and it depends on your use case. With this solution, you are not sharing your email address. You are giving people a way to contact you. What if people want to email you? What if people are looking for your email address, and they don’t want a contact form? A contact form may be a heavy-handed solution in that sort of situation.


We reached the end! In this tutorial, we talked about different solutions to the problem of online email sharing. We walked through different ideas, involving HTML code, JavaScript and even some online services like Formspree to build contact forms. At the end of this tutorial, you should be aware of all the pros and cons of the strategies shown. Now, it’s up to you to pick up the most suitable one for the your specific use case.

How to Safely Share Your Email Address on a Website originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Using Web Components With Next (or Any SSR Framework)

Css Tricks - Wed, 10/05/2022 - 3:05am

In my previous post we looked at Shoelace, which is a component library with a full suite of UX components that are beautiful, accessible, and — perhaps unexpectedly — built with Web Components. This means they can be used with any JavaScript framework. While React’s Web Component interoperability is, at present, less than ideal, there are workarounds.

But one serious shortcoming of Web Components is their current lack of support for server-side rendering (SSR). There is something called the Declarative Shadow DOM (DSD) in the works, but current support for it is pretty minimal, and it actually requires buy-in from your web server to emit special markup for the DSD. There’s currently work being done for Next.js that I look forward to seeing. But for this post, we’ll look at how to manage Web Components from any SSR framework, like Next.js, today.

We’ll wind up doing a non-trivial amount of manual work, and slightly hurting our page’s startup performance in the process. We’ll then look at how to minimize these performance costs. But make no mistake: this solution is not without tradeoffs, so don’t expect otherwise. Always measure and profile.

The problem

Before we dive in, let’s take a moment and actually explain the problem. Why don’t Web Components work well with server-side rendering?

Application frameworks like Next.js take React code and run it through an API to essentially “stringify” it, meaning it turns your components into plain HTML. So the React component tree will render on the server hosting the web app, and that HTML will be sent down with the rest of the web app’s HTML document to your user’s browser. Along with this HTML are some <script> tags that load React, along with the code for all your React components. When a browser processes these <script> tags, React will re-render the component tree, and match things up with the SSR’d HTML that was sent down. At this point, all of the effects will start running, the event handlers will wire up, and the state will actually… contain state. It’s at this point that the web app becomes interactive. The process of re-processing your component tree on the client, and wiring everything up is called hydration.

So, what does this have to do with Web Components? Well, when you render something, say the same Shoelace <sl-tab-group> component we visited last time:

<sl-tab-group ref="{tabsRef}"> <sl-tab slot="nav" panel="general"> General </sl-tab> <sl-tab slot="nav" panel="custom"> Custom </sl-tab> <sl-tab slot="nav" panel="advanced"> Advanced </sl-tab> <sl-tab slot="nav" panel="disabled" disabled> Disabled </sl-tab> <sl-tab-panel name="general">This is the general tab panel.</sl-tab-panel> <sl-tab-panel name="custom">This is the custom tab panel.</sl-tab-panel> <sl-tab-panel name="advanced">This is the advanced tab panel.</sl-tab-panel> <sl-tab-panel name="disabled">This is a disabled tab panel.</sl-tab-panel> </sl-tab-group>

…React (or honestly any JavaScript framework) will see those tags and simply pass them along. React (or Svelte, or Solid) are not responsible for turning those tags into nicely-formatted tabs. The code for that is tucked away inside of whatever code you have that defines those Web Components. In our case, that code is in the Shoelace library, but the code can be anywhere. What’s important is when the code runs.

Normally, the code registering these Web Components will be pulled into your application’s normal code via a JavaScript import. That means this code will wind up in your JavaScript bundle and execute during hydration which means that, between your user first seeing the SSR’d HTML and hydration happening, these tabs (or any Web Component for that matter) will not render the correct content. Then, when hydration happens, the proper content will display, likely causing the content around these Web Components to move around and fit the properly formatted content. This is known as a flash of unstyled content, or FOUC. In theory, you could stick markup in between all of those <sl-tab-xyz> tags to match the finished output, but this is all but impossible in practice, especially for a third-party component library like Shoelace.

Moving our Web Component registration code

So the problem is that the code to make Web Components do what they need to do won’t actually run until hydration occurs. For this post, we’ll look at running that code sooner; immediately, in fact. We’ll look at custom bundling our Web Component code, and manually adding a script directly to our document’s <head> so it runs immediately, and blocks the rest of the document until it does. This is normally a terrible thing to do. The whole point of server-side rendering is to not block our page from processing until our JavaScript has processed. But once done, it means that, as the document is initially rendering our HTML from the server, the Web Components will be registered and will both immediately and synchronously emit the right content.

In our case, we’re just looking to run our Web Component registration code in a blocking script. This code isn’t huge, and we’ll look to significantly lessen the performance hit by adding some cache headers to help with subsequent visits. This isn’t a perfect solution. The first time a user browses your page will always block while that script file is loaded. Subsequent visits will cache nicely, but this tradeoff might not be feasible for you — e-commerce, anyone? Anyway, profile, measure, and make the right decision for your app. Besides, in the future it’s entirely possible Next.js will fully support DSD and Web Components.

Getting started

All of the code we’ll be looking at is in this GitHub repo and deployed here with Vercel. The web app renders some Shoelace components along with text that changes color and content upon hydration. You should be able to see the text change to “Hydrated,” with the Shoelace components already rendering properly.

Custom bundling Web Component code

Our first step is to create a single JavaScript module that imports all of our Web Component definitions. For the Shoelace components I’m using, my code looks like this:

import { setDefaultAnimation } from "@shoelace-style/shoelace/dist/utilities/animation-registry"; import "@shoelace-style/shoelace/dist/components/tab/tab.js"; import "@shoelace-style/shoelace/dist/components/tab-panel/tab-panel.js"; import "@shoelace-style/shoelace/dist/components/tab-group/tab-group.js"; import "@shoelace-style/shoelace/dist/components/dialog/dialog.js"; setDefaultAnimation("dialog.show", { keyframes: [ { opacity: 0, transform: "translate3d(0px, -20px, 0px)" }, { opacity: 1, transform: "translate3d(0px, 0px, 0px)" }, ], options: { duration: 250, easing: "cubic-bezier(0.785, 0.135, 0.150, 0.860)" }, }); setDefaultAnimation("dialog.hide", { keyframes: [ { opacity: 1, transform: "translate3d(0px, 0px, 0px)" }, { opacity: 0, transform: "translate3d(0px, 20px, 0px)" }, ], options: { duration: 250, easing: "cubic-bezier(0.785, 0.135, 0.150, 0.860)" }, });

It loads the definitions for the <sl-tab-group> and <sl-dialog> components, and overrides some default animations for the dialog. Simple enough. But the interesting piece here is getting this code into our application. We cannot simply import this module. If we did that, it’d get bundled into our normal JavaScript bundles and run during hydration. This would cause the FOUC we’re trying to avoid.

While Next.js does have a number of webpack hooks to custom bundle things, I’ll use Vite instead. First, install it with npm i vite and then create a vite.config.js file. Mine looks like this:

import { defineConfig } from "vite"; import path from "path"; export default defineConfig({ build: { outDir: path.join(__dirname, "./shoelace-dir"), lib: { name: "shoelace", entry: "./src/shoelace-bundle.js", formats: ["umd"], fileName: () => "shoelace-bundle.js", }, rollupOptions: { output: { entryFileNames: `[name]-[hash].js`, }, }, }, });

This will build a bundle file with our Web Component definitions in the shoelace-dir folder. Let’s move it over to the public folder so that Next.js will serve it. And we should also keep track of the exact name of the file, with the hash on the end of it. Here’s a Node script that moves the file and writes a JavaScript module that exports a simple constant with the name of the bundle file (this will come in handy shortly):

const fs = require("fs"); const path = require("path"); const shoelaceOutputPath = path.join(process.cwd(), "shoelace-dir"); const publicShoelacePath = path.join(process.cwd(), "public", "shoelace"); const files = fs.readdirSync(shoelaceOutputPath); const shoelaceBundleFile = files.find(name => /^shoelace-bundle/.test(name)); fs.rmSync(publicShoelacePath, { force: true, recursive: true }); fs.mkdirSync(publicShoelacePath, { recursive: true }); fs.renameSync(path.join(shoelaceOutputPath, shoelaceBundleFile), path.join(publicShoelacePath, shoelaceBundleFile)); fs.rmSync(shoelaceOutputPath, { force: true, recursive: true }); fs.writeFileSync(path.join(process.cwd(), "util", "shoelace-bundle-info.js"), `export const shoelacePath = "/shoelace/${shoelaceBundleFile}";`);

Here’s a companion npm script:

"bundle-shoelace": "vite build && node util/process-shoelace-bundle",

That should work. For me, util/shoelace-bundle-info.js now exists, and looks like this:

export const shoelacePath = "/shoelace/shoelace-bundle-a6f19317.js"; Loading the script

Let’s go into the Next.js \_document.js file and pull in the name of our Web Component bundle file:

import { shoelacePath } from "../util/shoelace-bundle-info";

Then we manually render a <script> tag in the <head>. Here’s what my entire _document.js file looks like:

import { Html, Head, Main, NextScript } from "next/document"; import { shoelacePath } from "../util/shoelace-bundle-info"; export default function Document() { return ( <Html> <Head> <script src={shoelacePath}></script> </Head> <body> <Main /> <NextScript /> </body> </Html> ); }

And that should work! Our Shoelace registration will load in a blocking script and be available immediately as our page processes the initial HTML.

Improving performance

We could leave things as they are but let’s add caching for our Shoelace bundle. We’ll tell Next.js to make these Shoelace bundles cacheable by adding the following entry to our Next.js config file:

async headers() { return [ { source: "/shoelace/shoelace-bundle-:hash.js", headers: [ { key: "Cache-Control", value: "public,max-age=31536000,immutable", }, ], }, ]; }

Now, on subsequent browses to our site, we see the Shoelace bundle caching nicely!

If our Shoelace bundle ever changes, the file name will change (via the :hash portion from the source property above), the browser will find that it does not have that file cached, and will simply request it fresh from the network.

Wrapping up

This may have seemed like a lot of manual work; and it was. It’s unfortunate Web Components don’t offer better out-of-the-box support for server-side rendering.

But we shouldn’t forget the benefits they provide: it’s nice being able to use quality UX components that aren’t tied to a specific framework. It’s aldo nice being able to experiment with brand new frameworks, like Solid, without needing to find (or hack together) some sort of tab, modal, autocomplete, or whatever component.

Using Web Components With Next (or Any SSR Framework) originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

State of CSS 2022 Survey Now Open

Css Tricks - Tue, 10/04/2022 - 8:35am

The State of CSS survey recently opened up. Last year, the survey confirmed everyone’s assumptions that TailwindCSS is super popular and CSS variables are mainstream. It also codified what many of us want from CSS, from Container Queries to a parent selector. (Spoiler alert, we now have both of ’em.)

While I wouldn’t say the results have been super surprising each year, this time I’m excited to start seeing more historical trends reveal themselves. The survey has been running since 2019, so that’s going to be four years (ancient in front-end years!) of data to see if certain frameworks came and went, specific features are gaining momentum, what general learning practices are out there, and just plain more context. It takes time for stuff to build up like this, so kudos to Sacha Greif for keeping this thing going.

And speaking of the team behind the survey, Lea Verou is new to the bunch and lead this year’s edition. Lea made some nice additions, including more open-ended comments, questions about browser inconsistencies, and a question that compares the amount of time you write CSS versus JavaScript.

Browsers actually use this stuff to help prioritize what features to work on — so definitely add your voice to the mix! The polls close on October 20.

To Shared LinkPermalink on CSS-Tricks

State of CSS 2022 Survey Now Open originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Introducing Shoelace, a Framework-Independent Component-Based UX Library

Css Tricks - Tue, 10/04/2022 - 3:01am

This is a post about Shoelace, a component library by Cory LaViska, but with a twist. It defines all your standard UX components: tabs, modals, accordions, auto-completes, and much, much more. They look beautiful out of the box, are accessible, and fully customizable. But rather than creating these components in React, or Solid, or Svelte, etc., it creates them with Web Components; this means you can use them with any framework.

Some preliminary things

Web Components are great, but there’s currently a few small hitches to be aware of.


I said they work in any JavaScript framework, but as I’ve written before, React’s support for Web Components is currently poor. To address this, Shoelace actually created wrappers just for React.

Another option, which I personally like, is to create a thin React component that accepts the tag name of a Web Component and all of its attributes and properties, then does the dirty work of handling React’s shortcomings. I talked about this option in a previous post. I like this solution because it’s designed to be deleted. The Web Component interoperability problem is currently fixed in React’s experimental branch, so once that’s shipped, any thin Web Component-interoperable component you’re using could be searched, and removed, leaving you with direct Web Component usages, without any React wrappers.

Server-Side Rendering (SSR)

Support for SSR is also poor at the time of this writing. In theory, there’s something called Declarative Shadow DOM (DSD) which would enable SSR. But browser support is minimal, and in any event, DSD actually requires server support to work right, which means Next, Remix, or whatever you happen to use on the server will need to become capable of some special handling.

That said, there are other ways to get Web Components to just work with a web app that’s SSR’d with something like Next. The short version is that the scripts registering your Web Components need to run in a blocking script before your markup is parsed. But that’s a topic for another post.

Of course, if you’re building any kind of client-rendered SPA, this is a non-issue. This is what we’ll work with in this post.

Let’s start

Since I want this post to focus on Shoelace and on its Web Component nature, I’ll be using Svelte for everything. I’ll also be using this Stackblitz project for demonstration. We’ll build this demo together, step-by-step, but feel free to open that REPL up anytime to see the end result.

I’ll show you how to use Shoelace, and more importantly, how to customize it. We’ll talk about Shadow DOMs and which styles they block from the outside world (as well as which ones they don’t). We’ll also talk about the ::part CSS selector — which may be entirely new to you — and we’ll even see how Shoelace allows us to override and customize its various animations.

If you find you like Shoelace after reading this post and want to try it in a React project, my advice is to use a wrapper like I mentioned in the introduction. This will allow you to use any of Shoelace’s components, and it can be removed altogether once React ships the Web Component fixes they already have (look for that in version 19).

Introducing Shoelace

Shoelace has fairly detailed installation instructions. At its most simple, you can dump <script> and <style> tags into your HTML doc, and that’s that. For any production app, though, you’ll probably want to selectively import only what you want, and there are instructions for that, too.

With Shoelace installed, let’s create a Svelte component to render some content, and then go through the steps to fully customize it. To pick something fairly non-trivial, I went with the tabs and a dialog (commonly referred to as a modal) components. Here’s some markup taken largely from the docs:

<sl-tab-group> <sl-tab slot="nav" panel="general">General</sl-tab> <sl-tab slot="nav" panel="custom">Custom</sl-tab> <sl-tab slot="nav" panel="advanced">Advanced</sl-tab> <sl-tab slot="nav" panel="disabled" disabled>Disabled</sl-tab> <sl-tab-panel name="general">This is the general tab panel.</sl-tab-panel> <sl-tab-panel name="custom">This is the custom tab panel.</sl-tab-panel> <sl-tab-panel name="advanced">This is the advanced tab panel.</sl-tab-panel> <sl-tab-panel name="disabled">This is a disabled tab panel.</sl-tab-panel> </sl-tab-group> <sl-dialog no-header label="Dialog"> Hello World! <button slot="footer" variant="primary">Close</button> </sl-dialog> <br /> <button>Open Dialog</button>

This renders some nice, styled tabs. The underline on the active tab even animates nicely, and slides from one active tab to the next.

Default tabs in Shoelace

I won’t waste your time running through every inch of the APIs that are already well-documented on the Shoelace website. Instead, let’s look into how best to interact with, and fully customize these Web Components.

Interacting with the API: methods and events

Calling methods and subscribing to events on a Web Component might be slightly different than what you’re used to with your normal framework of choice, but it’s not too complicated. Let’s see how.


The tabs component (<sl-tab-group>) has a show method, which manually shows a particular tab. In order to call this, we need to get access to the underlying DOM element of our tabs. In Svelte, that means using bind:this. In React, it’d be a ref. And so on. Since we’re using Svelte, let’s declare a variable for our tabs instance:

<script> let tabs; </script>

…and bind it:

<sl-tab-group bind:this="{tabs}"></sl-tab-group>

Now we can add a button to call it:

<button on:click={() => tabs.show("custom")}>Show custom</button>

It’s the same idea for events. There’s a sl-tab-show event that fires when a new tab is shown. We could use addEventListener on our tabs variable, or we can use Svelte’s on:event-name shortcut.

<sl-tab-group bind:this={tabs} on:sl-tab-show={e => console.log(e)}>

That works and logs the event objects as you show different tabs.

Typically we render tabs and let the user click between them, so this work isn’t usually even necessary, but it’s there if you need it. Now let’s get the dialog component interactive.


The dialog component (<sl-dialog>) takes an open prop which controls whether the dialog is… open. Let’s declare it in our Svelte component:

<script> let tabs; let open = false; </script>

It also has an sl-hide event for when the dialog is hidden. Let’s pass our open prop and bind to the hide event so we can reset it when the user clicks outside of the dialog content to close it. And let’s add a click handler to that close button to set our open prop to false, which would also close the dialog.

<sl-dialog no-header {open} label="Dialog" on:sl-hide={() => open = false}> Hello World! <button slot="footer" variant="primary" on:click={() => open = false}>Close</button> </sl-dialog>

Lastly, let’s wire up our open dialog button:

<button on:click={() => (open = true)}>Open Dialog</button>

And that’s that. Interacting with a component library’s API is more or less straightforward. If that’s all this post did, it would be pretty boring.

But Shoelace — being built with Web Components — means that some things, particularly styles, will work a bit differently than we might be used to.

Customize all the styles!

As of this writing, Shoelace is still in beta and the creator is considering changing some default styles, possibly even removing some defaults altogether so they’ll no longer override your host application’s styles. The concepts we’ll cover are relevant either way, but don’t be surprised if some of the Shoelace specifics I mention are different when you go to use it.

As nice as Shoelace’s default styles are, we might have our own designs in our web app, and we’ll want our UX components to match. Let’s see how we’d go about that in a Web Components world.

We won’t try to actually improve anything. The Shoelace creator is a far better designer than I’ll ever be. Instead, we’ll just look at how to change things, so you can adapt to your own web apps.

A quick tour of Shadow DOMs

Take a peek at one of those tab headers in your DevTools; it should look something like this:

Our tab element has created a div container with a .tab and .tab--active class, and a tabindex, while also displaying the text we entered for that tab. But notice that it’s sitting inside of a shadow root. This allows Web Component authors to add their own markup to the Web Component while also providing a place for the content we provide. Notice the <slot> element? That basically means “put whatever content the user rendered between the Web Component tags here.”

So the <sl-tab> component creates a shadow root, adds some content to it to render the nicely-styled tab header along with a placeholder (<slot>) that renders our content inside.

Encapsulated styles

One of the classic, more frustrating problems in web development has always been styles cascading to places where we don’t want them. You might worry that any style rules in our application which specify something like div.tab would interfere with these tabs. It turns out this isn’t a problem; shadow roots encapsulate styles. Styles from outside the shadow root do not affect what’s inside the shadow root (with some exceptions which we’ll talk about), and vice versa.

The exceptions to this are inheritable styles. You, of course, don’t need to apply a font-family style for every element in your web app. Instead, you can specify your font-family once, on :root or html and have it inherit everywhere beneath it. This inheritance will, in fact, pierce the shadow root as well.

CSS custom properties (often called “css variables”) are a related exception. A shadow root can absolutely read a CSS property that is defined outside the shadow root; this will become relevant in a moment.

The ::part selector

What about styles that don’t inherit. What if we want to customize something like cursor, which doesn’t inherit, on something inside of the shadow root. Are we out of luck? It turns out we’re not. Take another look at the tab element image above and its shadow root. Notice the part attribute on the div? That allows you to target and style that element from outside the shadow root using the ::part selector. We’ll walk through an example is a bit.

Overriding Shoelace styles

Let’s see each of these approaches in action. As of now, a lot of Shoelace styles, including fonts, receive default values from CSS custom properties. To align those fonts with your application’s styles, override the custom props in question. See the docs for info on which CSS variables Shoelace is using, or you can simply inspect the styles in any given element in DevTools.

Inheriting styles through the shadow root

Open the app.css file in the src directory of the StackBlitz project. In the :root section at the bottom, you should see a letter-spacing: normal; declaration. Since the letter-spacing property is inheritable, try setting a new value, like 2px. On save, all content, including the tab headers defined in the shadow root, will adjust accordingly.

Overwriting Shoelace CSS variables

The <sl-tab-group> component reads an --indicator-color CSS custom property for the active tab’s underline. We can override this with some basic CSS:

sl-tab-group { --indicator-color: green; }

And just like that, we now have a green indicator!

Querying parts

In the version of Shoelace I’m using right now (2.0.0-beta.83), any non-disabled tab has a pointer cursor. Let’s change that to a default cursor for the active (selected) tab. We already saw that the <sl-tab> element adds a part="base" attribute on the container for the tab header. Also, the currently selected tab receives an active attribute. Let’s use these facts to target the active tab, and change the cursor:

sl-tab[active]::part(base) { cursor: default; }

And that’s that!

Customizing animations

For some icing on the metaphorical cake, let’s see how Shoelace allows us to customize animations. Shoelace uses the Web Animations API, and exposes a setDefaultAnimation API to control how different elements animate their various interactions. See the docs for specifics, but as an example, here’s how you might change Shoelace’s default dialog animation from expanding outward, and shrinking inward, to instead animate in from the top, and drop down while hiding.

import { setDefaultAnimation } from "@shoelace-style/shoelace/dist/utilities/animation-registry"; setDefaultAnimation("dialog.show", { keyframes: [ { opacity: 0, transform: "translate3d(0px, -20px, 0px)" }, { opacity: 1, transform: "translate3d(0px, 0px, 0px)" }, ], options: { duration: 250, easing: "cubic-bezier(0.785, 0.135, 0.150, 0.860)" }, }); setDefaultAnimation("dialog.hide", { keyframes: [ { opacity: 1, transform: "translate3d(0px, 0px, 0px)" }, { opacity: 0, transform: "translate3d(0px, 20px, 0px)" }, ], options: { duration: 200, easing: "cubic-bezier(0.785, 0.135, 0.150, 0.860)" }, });

That code is in the App.svelte file. Comment it out to see the original, default animation.

Wrapping up

Shoelace is an incredibly ambitious component library that’s built with Web Components. Since Web Components are framework-independent, they can be used in any project, with any framework. With new frameworks starting to come out with both amazing performance characteristics, and also ease of use, the ability to use quality user experience widgets which aren’t tied to any one framework has never been more compelling.

Introducing Shoelace, a Framework-Independent Component-Based UX Library originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Named Element IDs Can Be Referenced as JavaScript Globals

Css Tricks - Tue, 09/27/2022 - 2:58am

Did you know that DOM elements with IDs are accessible in JavaScript as global variables? It’s one of those things that’s been around, like, forever but I’m really digging into it for the first time.

If this is the first time you’re hearing about it, brace yourself! We can see it in action simply by adding an ID to an element in HTML:

<div id="cool"></div>

Normally, we’d define a new variable using querySelector("#cool") or getElementById("cool") to select that element:

var el = querySelector("#cool");

But we actually already have access to #cool without that rigamorale:

CodePen Embed Fallback

So, any id — or name attribute, for that matter — in the HTML can be accessed in JavaScript using window[ELEMENT_ID]. Again, this isn’t exactly “new” but it’s really uncommon to see.

As you may guess, accessing the global scope with named references isn’t the greatest idea. Some folks have come to call this the “global scope polluter.” We’ll get into why that is, but first…

Some context

This approach is outlined in the HTML specification, where it’s described as “named access on the Window object.”

Internet Explorer was the first to implement the feature. All other browsers added it as well. Gecko was the only browser at the time to not support it directly in standards mode, opting instead to make it an experimental feature. There was hesitation to implement it at all, but it moved ahead in the name of browser compatibility (Gecko even tried to convince WebKit to move it out of standards mode) and eventually made it to standards mode in Firefox 14.

One thing that might not be well known is that browsers had to put in place a few precautionary measures — with varying degrees of success — to ensure generated globals don’t break the webpage. One such measure is…

Variable shadowing

Probably the most interesting part of this feature is that named element references don’t shadow existing global variables. So, if a DOM element has an id that is already defined as a global, it won’t override the existing one. For example:

<head> <script> window.foo = "bar"; </script> </head> <body> <div id="foo">I won't override window.foo</div> <script> console.log(window.foo); // Prints "bar" </script> </body>

And the opposite is true as well:

<div id="foo">I will be overridden :(</div> <script> window.foo = "bar"; console.log(window.foo); // Prints "bar" </script>

This behavior is essential because it nullifies dangerous overrides such as <div id="alert" />, which would otherwise create a conflict by invalidating the alert API. This safeguarding technique may very well be the why you — if you’re like me — are learning about this for the first time.

The case against named globals

Earlier, I said that using global named elements as references might not be the greatest idea. There are lots of reasons for that, which TJ VanToll has covered nicely over at his blog and I will summarize here:

  • If the DOM changes, then so does the reference. That makes for some really “brittle” (the spec’s term for it) code where the separation of concerns between HTML and JavaScript might be too much.
  • Accidental references are far too easy. A simple typo may very well wind up referencing a named global and give you unexpected results.
  • It is implemented differently in browsers. For example, we should be able to access an anchor with an id — e.g. <a id="cool"> — but some browsers (namely Safari and Firefox) return a ReferenceError in the console.
  • It might not return what you think. According to the spec, when there are multiple instances of the same named element in the DOM — say, two instances of <div class="cool"> — the browser should return an HTMLCollection with an array of the instances. Firefox, however, only returns the first instance. Then again, the spec says we ought to use one instance of an id in an element’s tree anyway. But doing so won’t stop a page from working or anything like that.
  • Maybe there’s a performance cost? I mean, the browser’s gotta make that list of references and maintain it. A couple of folks ran tests in this StackOverflow thread, where named globals were actually more performant in one test and less performant in a more recent test.
Additional considerations

Let’s say we chuck the criticisms against using named globals and use them anyway. It’s all good. But there are some things you might want to consider as you do.


As edge-case-y as it may sound, these types of global checks are a typical setup requirement for polyfills. Check out the following example where we set a cookie using the new CookieStore API, polyfilling it on browsers that don’t support it yet:

<body> <img id="cookieStore"></img> <script> // Polyfill the CookieStore API if not yet implemented. // https://developer.mozilla.org/en-US/docs/Web/API/CookieStore if (!window.cookieStore) { window.cookieStore = myCookieStorePolyfill; } cookieStore.set("foo", "bar"); </script> </body>

This code works perfectly fine in Chrome, but throws the following error in Safari.:

TypeError: cookieStore.set is not a function

Safari lacks support for the CookieStore API as of this writing. As a result, the polyfill is not applied because the img element ID creates a global variable that clashes with the cookieStore global.

JavaScript API updates

We can flip the situation and find yet another issue where updates to the browser’s JavaScript engine can break a named element’s global references.

For example:

<body> <input id="BarcodeDetector"></input> <script> window.BarcodeDetector.focus(); </script> </body>

That script grabs a reference to the input element and invokes focus() on it. It works correctly. Still, we don’t know how long it will continue to work.

You see, the global variable we’re using to reference the input element will stop working as soon as browsers start supporting the BarcodeDetector API. At that point, the window.BarcodeDetector global will no longer be a reference to the input element and .focus() will throw a “window.BarcodeDetector.focus is not a function” error.


Let’s sum up how we got here:

  • All major browsers automatically create global references to each DOM element with an id (or, in some cases, a name attribute).
  • Accessing these elements through their global references is unreliable and potentially dangerous. Use querySelector or getElementById instead.
  • Since global references are generated automatically, they may have some side effects on your code. That’s a good reason to avoid using the id attribute unless you really need it.

At the end of the day, it’s probably a good idea to avoid using named globals in JavaScript. I quoted the spec earlier about how it leads to “brittle” code, but here’s the full text to drive the point home:

As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the web platform, for example. Instead of this, use document.getElementById() or document.querySelector().

I think the fact that the HTML spec itself recommends to staying away from this feature speaks for itself.

Named Element IDs Can Be Referenced as JavaScript Globals originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Syndicate content
©2003 - Present Akamai Design & Development.