Archiwum kategorii: CSS

Fit width text in 1 line of CSS

Post pobrano z: Fit width text in 1 line of CSS

From Adam, prototyped in Chrome Canary 145:

h1 {
  text-grow: per-line scale;
}

Danny discussed this a while back when looking at different approaches for fitting text to a container, spelling out the syntax (text-shrink included) that you can find in Roma Komarov’s explainer:

text-grow: <fit-target> <fit-method>? <length>?;
text-shrink: <fit-target> <fit-method>? <length>?;
  • <fit-target>
    • per-line: For text-grow, lines of text shorter than the container will grow to fit it. For text-shrink, lines of text longer than the container will shrink to fit it.
    • consistent: For text-grow, the shortest line will grow to fit the container while all other lines grow by the same scaling factor. For text-shrink, the longest line will shrink to fit the container while all other lines shrink by the same scaling factor.
  • <fit-method> (optional)
    • scale: Scale the glyphs instead of changing the font-size.
    • scale-inline: Scale the glyphs instead of changing the font-size, but only horizontally.
    • font-size: Grow or shrink the font size accordingly.
    • letter-spacing: The letter spacing will grow/shrink instead of the font-size.
  • <length> (optional): The maximum font size for text-grow or minimum font size for text-shrink.

Notice the different fit methods — they either scale the glyphs or adjust the text’s actual font-size. So, naturally, the explainer notes that accessibility concerns are still being worked out. Like:

If an end-user tries to enlarge font size, UAs should not fit enlarged lines to the container width. Is minimum-font setting enough?

Speaking of open questions, Una Kravets highlights a few on Bluesky:

  • Should the last line of a paragraph be scaled?
  • Is the current line-height behavior as expected?
  • Should it scale non-text parts such as inline images together?

You can contribute to the discussion in the GitHub issue, of course.

Donnie D’Amato wonders if, perhaps, this idea is better suited for print styles rather than screens. That’s an excellent use case I hadn’t thought of.

We sure have come a long way from the days of magic numbers and FitText.js!


Fit width text in 1 line of CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

What Else Could Container Queries… Query?

Post pobrano z: What Else Could Container Queries… Query?

I’ll admit, when container queries first shipped back in 2022, I didn’t really pay attention. I mean, why container size queries when we already have media queries? Why container style queries when custom properties inherit anyway (they don’t work with standard properties… yet)? Their use cases seemed like edge cases to me, enabling us to do things that we could already do but in a different way.

Here’s a container size queries demo by Kevin Powell. As a note, all major browsers support size queries in the following demo, but other demos in this article may require the latest Chrome.

CodePen Embed Fallback

Container style queries (with the new range syntax) demo by, uh, me:

CodePen Embed Fallback

And more recently, we’ve seen a couple more types of container queries pop up.

Container Scroll-State Queries

Container scroll-state queries came along with their unique capabilities — the ability to find out whether a container is scrollable, or is scroll-snapped to a scroll target, or has position: sticky and is ‘stuck.’ Literally, as I’m writing this, Chrome announced scrolled support, which is a bit different to scrollable.

Container scroll-state queries demo by our very own Geoff Graham:

CodePen Embed Fallback

And that’s not all we’ve got…

Anchored container queries

The latest container query feature is anchored container queries, which enable us to query fallback positions. Imagine that you anchor-position a tooltip caret to the left side of a tooltip, but then there’s no room to display the tooltip, so you flip it to the opposite side of whatever triggers it using position-try-fallbacks: flip-inline. Well, an anchored container query can detect when the tooltip position is flipped so that we can also flip the tooltip caret to the opposite side of the tooltip.

CodePen Embed Fallback

What else?

So, it got me thinking, how far can we really go with container queries? There are dozens of media queries now, so what if there were dozens of container queries as well? What could we use them for?

Get any computed value

Recently I was exploring the current and future methods of getting the value of a CSS property and using it with another property, and as you can imagine, container size queries were mentioned since they unlock container query units. I mean, have you ever added a wrapper element or defined an existing one as a container just to access container query units?

<parent> {
  /* Gimme container query units! */
  container-type: inline-size;

  <child> {
    width: 100cqi;
  }
}

Now, I don’t love container queries as a means of getting values because the syntax can be a bit long-winded for that (longer than the example above, and size queries in particular are a bit quirky), but the fact that we can use them to do a little more than querying is testament to how versatile they are as a feature. As an alternative, I suggested a CSS function called compute(), where if you wanted the height of something (or the “something” of anything), we could steal it from another element like this:

<parent> {
  <child> {
    /* Computed height of <child> */
    property: compute(height, self);
    /* Computed height of the parent */
    property: compute(height, inherit);
    /* Computed height of #abc element */
    property: compute(height, #abc);
  }
}

This would save us from having to implement a container size query just to use its container query units, and would also apply to all properties. Besides, a container size query wouldn’t help us to acquire the un-computed declared value that we actually typed out. For that, the inherit() function has been proposed and Roma even shows us how to use it in Chrome Canary.

To add, I really like the keyword approach and would love to see more keywords like currentColor (e.g., currentBackgroundColor has been proposed).

Still, if container queries could be extended to get the value of any CSS property, I definitely wouldn’t say no to that! The flexibility to pass properties/values between elements is way too enticing.

Query any CSS property

This feature has actually been on the slate since container style queries were first proposed, but there’s no telling when it will arrive. This container style query upgrade will enable us to query the (un-computed/declared) value of any CSS property instead of just custom properties (although you won’t be able to ‘get’ and use those values, at least as far as I know).

Any CSS property? Uh, doesn’t that make all of the other container queries redundant? Not quite, no.

Container scroll-state queries detect snapping and stickiness, for which there are no pseudo-classes — but maybe there should be? They also detect scrollability, since, for example, overflow: scroll and overflow: visible doesn’t mean that the content is actually overflowing, only that we’re allowed to scroll the container if it does. Finally, anchored container queries don’t query the position-try-fallbacks value, they detect when, for example, the position-area is flipped.

So, you know, they do a whole bunch of stuff, and that’s why this upgrade for container style queries won’t replace them. In fact, I can totally see dozens of new container query features hitting the web within the next few years.

So, what else could container queries do?

Before container queries were even a thing, great ideas were being put forward. Of course, some of them actually became container queries whereas others are still just that — great ideas that haven’t gone anywhere (again…yet?).

I’m confident that we’ll see these ideas realized at some point, either as container queries or as some other syntax. Heck, since it’s December, I’ll make it my prediction for 2026: container queries will rule 2026.

What else do you want container queries to do?

References


What Else Could Container Queries… Query? originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

CSS shape() Commands

Post pobrano z: CSS shape() Commands

The CSS shape() function recently gained support in both Chromium and WebKit browsers. It’s a way of drawing complex shapes when clipping elements with the clip-path property. We’ve had the ability to draw basic shapes for years — think circle, ellipse(), and polygon() — but no “easy” way to draw more complex shapes.

Well, that’s not entirely true. It’s true there was no “easy” way to draw shapes, but we’ve had the path() function for some time, which we can use to draw shapes using SVG commands directly in the function’s arguments. This is an example of an SVG path pulled straight from WebKit’s blog post linked above:

<svg viewBox="0 0 150 100" xmlns="http://www.w3.org/2000/svg">
  <path fill="black" d="M0 0 L 100 0 L 150 50 L 100 100 L 0 100 Q 50 50 0 0 z " />
</svg>

Which means we can yank those <path> coordinates and drop them into the path() function in CSS when clipping a shape out of an element:

.clipped {
  clip-path: path("M0 0 L 100 0 L 150 50 L 100 100 L 0 100 Q 50 50 0 0 z");
}

I totally understand what all of those letters and numbers are doing. Just kidding, I’d have to read up on that somewhere, like Myriam Frisano’s more recent “Useful Recipes For Writing Vectors By Hand” article. There’s a steep learning curve to all that, and not everyone — including me — is going down that nerdy, albeit interesting, road. Writing SVG by hand is a niche specialty, not something you’d expect the average front-ender to know. I doubt I’m alone in saying I’d rather draw those vectors in something like Figma first, export the SVG code, and copy-paste the resulting paths where I need them.

The shape() function is designed to be more, let’s say, CSS-y. We get new commands that tell the browser where to draw lines, arcs, and curves, just like path(), but we get to use plain English and native CSS units rather than unreadable letters and coordinates. That opens us up to even using CSS calc()-ulations in our drawings!

Here’s a fairly simple drawing I made from a couple of elements. You’ll want to view the demo in either Chrome 135+ or Safari 18.4+ to see what’s up.

CodePen Embed Fallback

So, instead of all those wonky coordinates we saw in path(), we get new terminology. This post is really me trying to wrap my head around what those new terms are and how they’re used.

In short, you start by telling shape() where the starting point should be when drawing. For example, we can say “from top left” using directional keywords to set the origin at the top-left corner of the element. We can also use CSS units to set that position, so “from 0 0” works as well. Once we establish that starting point, we get a set of commands we can use for drawing lines, arcs, and curves.

I figured a table would help.

Command What it means Usage Examples
line A line that is drawn using a coordinate pair The by keyword sets a coordinate pair used to determine the length of the line. line by -2px 3px
vline Vertical line The to keyword indicates where the line should end, based on the current starting point.

The by keyword sets a coordinate pair used to determine the length of the line.

vline to 50px
hline Horizontal line The to keyword indicates where the line should end, based on the current starting point.

The by keyword sets a coordinate pair used to determine the length of the line.

hline to 95%
arc An arc (oh, really?!). An elliptical one, that is, sort of like the rounded edges of a heart shape. The to keyword indicates where the arc should end.

The with keyword sets a pair of coordinates that tells the arc how far right and down the arc should slope.

The of keyword specifies the size of the ellipse that the arc is taken from. The first value provides the horizontal radius of the ellipse, and the second provides the vertical radius. I’m a little unclear on this one, even after playing with it.

arc to 10% 50% of 1%
curve A curved line The to keyword indicates where the curved line should end.

The with keyword sets “control points” that affect the shape of the curve, making it deep or shallow.

curve to 0% 100% with 50% 0%
smooth Adds a smooth Bézier curve command to the list of path data commands The to keyword indicates where the curve should end.

The by keyword sets a coordinate pair used to determine the length of the curve.

The with keyword specifies control points for the curve.

I have yet to see any examples of this in the wild, but let me know if you do, and I can add it here.

The spec is dense, as you might expect with a lot of moving pieces like this. Again, these are just my notes, but let me know if there’s additional nuance you think would be handy to include in the table.

Oh, another fun thing: you can adjust the shape() on hover/focus. The only thing is that I was unable to transition or animate it, at least in the current implementation.

CodePen Embed Fallback

CSS shape() Commands originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

State of Devs: A Survey for Every Developer

Post pobrano z: State of Devs: A Survey for Every Developer

I don’t know if I should say this on a website devoted to programming, but I sometimes feel like *lowers voice* coding is actually the least interesting part of our lives.

After all, last time I got excited meeting someone at a conference it was because we were both into bouldering, not because we both use React. And The Social Network won an Oscar for the way it displayed interpersonal drama, not for its depiction of Mark Zuckerberg’s PHP code. 

Yet for the past couple years, I’ve been running developer surveys (such as the State of JS and State of CSS) that only ask about code. It was time to fix that. 

A new kind of survey

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

I’m hoping to answer questions such as:

  • What are developers’ favorite recent movies and video games?
  • What kind of physical activity do developers practice?
  • How much sleep are we all getting?

But also address more serious topics, including:

  • What do developers like about their workplace?
  • What factors lead to workplace discrimination?
  • What global issues are developers most concerned with?

Reaching out to new audiences

Another benefit from branching out into new topics is the chance to reach out to new audiences.

It’s no secret that people who don’t fit the mold of the average developer (whether because of their gender, race, age, disabilities, or a myriad of other factors) often have a harder time getting involved in the community, and this also shows up in our data. 

In the past, we’ve tried various outreach strategies to help address these imbalances in survey participation, but the results haven’t always been as effective as we’d hoped. 

So this time, I thought I’d try something different and have the survey itself include more questions relevant to under-represented groups, asking about workplace discrimination:

Question: Have you ever experiences discrimination in the workplace based on any of the following factors?

As well as actions taken in response to said discrimination:

Question: Have you taken any of the following actions in response to workplace issues?

Yet while obtaining a more representative data sample as a result of this new focus would be ideal, it isn’t the only benefit. 

The most vulnerable among us are often the proverbial canaries in the coal mine, suffering first from issues or policies that will eventually affect the rest of the community as well, if left unchecked. 

So, facing these issues head-on is especially valuable now, at a time when “DEI” is becoming a new taboo, and a lot of the important work that has been done to make things slightly better over the past decade is at risk of being reversed.

The big questions

Finally, the survey also tries to go beyond work and daily life to address the broader questions that keep us up at night:

Question: What global issues are currently most concerning to you?

There’s been talk in recent years about keeping the workplace free of politics. And why I can certainly see the appeal in that, in 2025, it feels harder than ever to achieve that ideal. At a time when people are losing rights and governments are sliding towards authoritarianism, should we still pretend that everything is fine? Especially when you factor in the fact that the tech community is now a major political player in its own right…

So while I didn’t push too far in that direction for this first edition of the survey, one of my goals for the future is to get a better grasp of where exactly developers stand in terms of ideology and worldview. Is this a good idea, or should I keep my distance from any hot-button issues? Don’t hesitate to let me know what you think, or suggest any other topic I should be asking about next time. 

In the meantime, go take the survey, and help us get a better picture of who exactly we all are!


State of Devs: A Survey for Every Developer originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Revisiting Image Maps

Post pobrano z: Revisiting Image Maps

I mentioned last time that I’ve been working on a new website for Emmy-award-winning game composer Mike Worth. He hired me to create a highly graphical design that showcases his work.

Mike loves ’90s animation, particularly Disney’s Duck Tales and other animated series. He challenged me to find a way to incorporate their retro ’90s style into his design without making it a pastiche. But that wasn’t my only challenge. I also needed to achieve that ’90s feel by using up-to-the-minute code to maintain accessibility, performance, responsiveness, and semantics.

Design by Andy Clarke, Stuff & Nonsense. Mike Worth’s website will launch in April 2025, but you can see examples from this article on CodePen.

Designing for Mike was like a trip back to when mainstream website design seemed more spontaneous and less governed by conventions and best practices. Some people describe these designs as “whimsical”:

adjective

  1. spontaneously fanciful or playful
  2. given to whims; capricious
  3. quaint, unusual, or fantastic

Collins English Dictionary

But I’m not so sure that’s entirely accurate. “Playful?” Definitely. “Fanciful?” Possibly. But “fantastic?” That depends. “Whimsy” sounds superfluous, so I call it “expressive” instead.

Studying design from way back, I remembered how websites often included graphics that combined branding, content, and navigation. Pretty much every reference to web design in the ’90s — when I designed my first website — talks about Warner Brothers’ Space Jam from 1996.

Space Jam website homepage. The movie logo is in the center of a series of planets that are navigation for other areas of the website against a dark starry background.
Warner Brothers’ Space Jam (1996)

So, I’m not going to do that.

Brands like Nintendo used their home pages to direct people to their content while making branded visual statements. Cheestrings combined graphics with navigation, making me wonder why we don’t see designs like this today. Goosebumps typified this approach, combining cartoon illustrations with brightly colored shapes into a functional and visually rich banner, proving that being useful doesn’t mean being boring.

Left to right: Nintendo, Cheestrings, Goosebumps.

In the ’90s, when I developed graphics for websites like these, I either sliced them up and put their parts in tables or used mostly forgotten image maps.

A brief overview of properties and values

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements. They were popular for graphics, maps, and navigation, but their use declined with the rise of CSS, SVG, and JavaScript.

<map> adds clickable areas to a bitmap or vector image.

<map name="projects">
  ...
</map>

That <map> is linked to an image using the usemap attribute:

<img usemap="#projects" ...>

Those elements can have separate href and alt attributes and can be enhanced with ARIA to improve accessibility:

<map name="projects">
  <area href="" alt="" … />
  ...
</map>

The shape attribute specifies an area’s shape. It can be a primitive circle or rect or a polygon defined by a set of absolute x and y coordinates:

<area shape="circle" coords="..." ... />
<area shape="rect" coords="..." ... />
<area shape="poly" coords="..." ... />

Despite their age, image maps still offer plenty of benefits. They’re lightweight and need (almost) no JavaScript. More on that in just a minute. They’re accessible and semantic when used with alt, ARIA, and title attributes. Despite being from a different era, even modern mobile browsers support image maps.

A large illustrated map of a cartoon island.
Design by Andy Clarke, Stuff & Nonsense. Mike Worth’s website will launch in April 2025, but you can see examples from this article on CodePen.

My design for Mike Worth includes several graphic navigation elements, which made me wonder if image maps might still be an appropriate solution.

Image maps in action

Mike wants his website to showcase his past work and the projects he’d like to do. To make this aspect of his design discoverable and fun, I created a map for people to explore by pressing on areas of the map to open modals. This map contains numbered circles, and pressing one pops up its modal.

A large illustrated cartoon map of an island. 6 annotations are on the map and a tooltip is exposed showing detail of one of the annotations.

My first thought was to embed anchors into the external map SVG:

<img src="projects.svg" alt="Projects">

<svg ...>
  ...
  <a href="...">
    <circle cx="35" cy="35" r="35" fill="#941B2F"/>
    <path fill="#FFF" d="..."/>
  </a>
</svg>

This approach is problematic. Those anchors are only active when SVG is inline and don’t work with an <img> element. But image maps work perfectly, even though specifying their coordinates can be laborious. Fortunately, plenty of tools are available, which make defining coordinates less tedious. Upload an image, choose shape types, draw the shapes, and copy the markup:

<img src="projects.svg" usemap="#projects-map.svg">

<map name="projects-map.svg">
  <area href="" alt="" coords="..." shape="circle">
  <area href="" alt="" coords="..." shape="circle">
  ...
</map>

Image maps work well when images are fixed sizes, but flexible images present a problem because map coordinates are absolute, not relative to an image’s dimensions. Making image maps responsive needs a little JavaScript to recalculate those coordinates when the image changes size:

function resizeMap() {
  const image = document.getElementById("projects");
  const map = document.querySelector("map[name='projects-map']");
  
  if (!image || !map || !image.naturalWidth) return;
  
  const scale = image.clientWidth / image.naturalWidth;
  map.querySelectorAll("area").forEach(area => {
  
    if (!area.dataset.originalCoords) {
      area.dataset.originalCoords = area.getAttribute("coords");
    }

    const scaledCoords = area.dataset.originalCoords
    
    .split(",")
    .map(coord => Math.round(coord * scale))
    .join(",");
    area.setAttribute("coords", scaledCoords);
  });
}

["load", "resize"].forEach(event =>
  window.addEventListener(event, resizeMap)
);

I still wasn’t happy with this implementation as I wanted someone to be able to press on much larger map areas, not just the numbered circles.

Every <path> has coordinates which define how it’s drawn, and they’re relative to the SVG viewBox:

<svg width="1024" height="1024">
  <path fill="#BFBFBF" d="…"/>
</svg>

On the other hand, a map’s <area> coordinates are absolute to the top-left of an image, so <path> values need to be converted. Fortunately, Raphael Monnerat has written PathToPoints, a tool which does precisely that. Upload an SVG, choose the point frequency, copy the coordinates for each path, and add them to a map area’s coords:

<map>
  <area href="" shape="poly" coords="...">
  <area href="" shape="poly" coords="...">
  <area href="" shape="poly" coords="...">
  ...
</map>

More issues with image maps

Image maps are hard-coded and time-consuming to create without tools. Even with tools for generating image maps, converting paths to points, and then recalculating them using JavaScript, they could be challenging to maintain at scale.

<area> elements aren’t visible, and except for a change in the cursor, they provide no visual feedback when someone hovers over or presses a link. Plus, there’s no easy way to add animations or interaction effects.

But the deal-breaker for me was that an image map’s pixel-based values are unresponsive by default. So, what might be an alternative solution for implementing my map using CSS, HTML, and SVG?

A large illustrated map of a cartoon island cut out against a transparent background.

Anchors positioned absolutely over my map wouldn’t solve the pixel-based positioning problem or give me the irregular-shaped clickable areas I wanted. Anchors within an external SVG wouldn’t work either.

But the solution was staring me in the face. I realized I needed to:

  1. Create a new SVG path for each clickable area.
  2. Make those paths invisible.
  3. Wrap each path inside an anchor.
  4. Place the anchors below other elements at the end of my SVG source.
  5. Replace that external file with inline SVG.
The same illustrated map of an island but the six regions are represented by solid colors.

I created a set of six much larger paths which define the clickable areas, each with its own fill to match its numbered circle. I placed each anchor at the end of my SVG source:

<svg … viewBox="0 0 1024 1024">

  <!-- Visible content -->
  <g>...</g>

  <!-- Clickable areas -->`
  <g id="links">`
    <a href="..."><path fill="#B48F4C" d="..."/></a>`
    <a href="..."><path fill="#6FA676" d="..."/></a>`
    <a href="..."><path fill="#30201D" d="..."/></a>`
    ...
  </g>
</svg>

Then, I reduced those anchors’ opacity to 0 and added a short transition to their full-opacity hover state:

#links a {
  opacity: 0;
  transition: all .25s ease-in-out;
}

#links a:hover {
  opacity: 1;
}

While using an image map’s <area> sadly provides no visual feedback, embedded anchors and their content can respond to someone’s action, hint at what’s to come, and add detail and depth to a design.

The illustrated regions of the cartoon map in three states, from left to right: annotated, with visual markers, and with both visual markers and labels.

I might add gloss to those numbered circles to be consistent with the branding I’ve designed for Mike. Or, I could include images, titles, or other content to preview the pop-up modals:

<g id="links">
  <a href="…">
    <path fill="#B48F4C" d="..."/>
    <image href="..." ... />
  </a>
</g>

Try it for yourself:

CodePen Embed Fallback

Expressive design, modern techniques

Designing Mike Worth’s website gave me a chance to blend expressive design with modern development techniques, and revisiting image maps reminded me just how important a tool image maps were during the period Mike loves so much.

Ultimately, image maps weren’t the right tool for Mike’s website. But exploring them helped me understand what I really needed: a way to recapture the expressiveness and personality of ’90s website design using modern techniques that are accessible, lightweight, responsive, and semantic. That’s what design’s about: choosing the right tool for a job, even if that sometimes means looking back to move forward.


Biography: Andy Clarke

Often referred to as one of the pioneers of web design, Andy Clarke has been instrumental in pushing the boundaries of web design and is known for his creative and visually stunning designs. His work has inspired countless designers to explore the full potential of product and website design.

Andy’s written several industry-leading books, including Transcending CSS, Hardboiled Web Design, and Art Direction for the Web. He’s also worked with businesses of all sizes and industries to achieve their goals through design.

Visit Andy’s studio, Stuff & Nonsense, and check out his Contract Killer, the popular web design contract template trusted by thousands of web designers and developers.


Revisiting Image Maps originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Modern Scroll Shadows Using Scroll-Driven Animations

Post pobrano z: Modern Scroll Shadows Using Scroll-Driven Animations

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before (indeed, it’s one of his all-time favorite CSS tricks), by layering background gradients with different attachments, we can get shadows that are covered up when you’ve scrolled to the limits of the element.

Geoff covered a newer approach that uses the animation-timeline property. Using animation-timeline, we can tie CSS animation to the scroll position. His example uses pseudo-elements to render the scroll shadows, and animation-range to animate the opacity of the pseudo-elements based on scroll.

Here’s yet another way. Instead of using shadows, let’s use a CSS mask to fade out the edges of the scrollable element. This is a slightly different visual metaphor that works great for horizontally scrollable elements — places where your scrollable element doesn’t have a distinct border of its own. This approach still uses animation-timeline, but we’ll use custom properties instead of pseudo-elements. Since we’re fading, the effect also works regardless of whether we’re on a dark or light background.

Getting started with a scrollable element

First, we’ll define our scrollable element with a mask that fades out the start and end of the container. For this example, let’s consider the infamous table that can’t be responsive and has to be horizontally scrollable on mobile.

Let’s add the mask. We can use the shorthand and find the mask as a linear gradient that fades out on either end. A mask lets the table fade into the background instead of overlaying a shadow, but you could use the same technique for shadows.

CodePen Embed Fallback
.scrollable {
  mask: linear-gradient(to right, #0000, #ffff 3rem calc(100% - 3rem), #0000);
}

Defining the custom properties and animation

Next, we need to define our custom properties and the animation. We’ll define two separate properties, --left-fade and --right-fade, using @property. Using @property is necessary here to specify the syntax of the properties so that browsers can animate the property’s values.

@property --left-fade {
  syntax: "<length>";
  inherits: false;
  initial-value: 0;
}

@property --right-fade {
  syntax: "<length>";
  inherits: false;
  initial-value: 0;
}

@keyframes scrollfade {
  0% {
    --left-fade: 0;
  }
  10%, 100% {
    --left-fade: 3rem;
  }
  0%, 90% {
    --right-fade: 3rem;
  }
  100% {
    --right-fade: 0;
  }
}

Instead of using multiple animations or animation-range, we can define a single animation where --left-fade animates from 0 to 3rem between 0-10%, and --right-fade animates from 3rem to 0 between 90-100%. Now we update our mask to use our custom properties and tie the scroll-timeline of our element to its own animation-timeline.

Putting it all together

Putting it all together, we have the effect we’re after:

CodePen Embed Fallback

We’re still waiting for some browsers (Safari) to support animation-timeline, but this gracefully degrades to simply not fading the element at all.

Wrapping up

I like this implementation because it combines two newer bits of CSS — animating custom properties and animation-timeline — to achieve a practical effect that’s more than just decoration. The technique can even be used with scroll-snap-based carousels or cards:

CodePen Embed Fallback

It works regardless of content or background and doesn’t require JavaScript. It exemplifies just how far CSS has come lately.


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

The Lost CSS Tricks of Cohost.org

Post pobrano z: The Lost CSS Tricks of Cohost.org

You would be forgiven if you’ve never heard of Cohost.org. The bespoke, Tumblr-like social media website came and went in a flash. Going public in June 2022 with invite-only registrations, Cohost’s peach and maroon landing page promised that it would be “posting, but better.” Just over two years later, in September 2024, the site announced its shutdown, its creators citing burnout and funding problems. Today, its servers are gone for good. Any link to cohost.org redirects to the Wayback Machine’s slow but comprehensive archive.

Screenshot of the Cohost.org homepage before it was shut down.

The landing page for Cohost.org, featuring our beloved eggbug.

Despite its short lifetime, I am confident in saying that Cohost delivered on its promise. This is in no small part due to its user base, consisting mostly of niche internet creatives and their friends — many of whom already considered “posting” to be an art form. These users were attracted to Cohost’s opinionated, anti-capitalist design that set it apart from the mainstream alternatives. The site was free of advertisements and follower counts, all feeds were purely chronological, and the posting interface even supported a subset of HTML.

It was this latter feature that conjured a community of its own. For security reasons, any post using HTML was passed through a sanitizer to remove any malicious or malformed elements. But unlike most websites, Cohost’s sanitizer was remarkably permissive. The vast majority of tags and attributes were allowed — most notably inline CSS styles on arbitrary elements.

Users didn’t take long to grasp the creative opportunities lurking within Cohost’s unassuming “new post” modal. Within 48 hours of going public, the fledgling community had figured out how to post poetry using the <details> tag, port the Apple homepage from 1999, and reimplement a quick-time WarioWare game. We called posts like these “CSS Crimes,” and the people who made them “CSS Criminals.” Without even intending to, the developers of Cohost had created an environment for a CSS community to thrive.

In this post, I’ll show you a few of the hacks we found while trying to push the limits of Cohost’s HTML support. Use these if you dare, lest you too get labelled a CSS criminal.

Width-hacking

Many of the CSS crimes of Cohost were powered by a technique that user @corncycle dubbed “width-hacking.” Using a combination of the <details> element and the CSS calc() function, we can get some pretty wild functionality: combination lockstile matching games, Zelda-style top-down movement, the list goes on.

If you’ve been around the CSS world for a while, there’s a good chance you’ve been exposed to the old checkbox hack. By combining a checkbox, a label, and creative use of CSS selectors, you can use the toggle functionality of the checkbox to implement all sorts of things. Tabbed areas, push toggles, dropdown menus, etc.

However, because this hack requires CSS selectors, that meant we couldn’t use it on Cohost — remember, we only had inline styles. Instead, we used the relatively new elements <details> and <summary>. These elements provide the same visibility-toggling logic, but now directly in HTML. No weird CSS needed.

CodePen Embed Fallback

These elements work like so: All children of the <details> element are hidden by default, except for the <summary> element. When the summary is clicked, it “opens” the parent details element, causing its children to become visible.

We can add all sorts of styles to these elements to make this example more interesting. Below, I have styled the constituent elements to create the effect of a button that lights up when you click on it.

CodePen Embed Fallback

This is achieved by giving the <summary> element a fixed position and size, a grey background color, and an outset border to make it look like a button. When it’s clicked, a sibling <div> is revealed that covers the <summary> with its own red background and border. Normally, this <div> would block further click events, but I’ve given it the declaration pointer-events: none. Now all clicks pass right on through to the <summary> element underneath, allowing you to turn the button back off.

This is all pretty nifty, but it’s ultimately the same logic as before: something is toggled either on or off. These are only two states. If we want to make games and other gizmos, we might want to represent hundreds to thousands of states.

Width-hacking gives us exactly that. Consider the following example:

CodePen Embed Fallback

In this example, three <details> elements live together in an inline-flex container. Because all the <summary> elements are absolutely-positioned, the width of their respective <details> elements are all zero when they’re closed.

Now, each of these three <details> has a small <div> inside. The first has a child with a width of 1px, the second a child with a width of 2px, and the third a width of 4px. When a <details> element is opened, it reveals its hidden <div>, causing its own width to increase. This increases the width of the inline-flex container. Because the width of the container is the sum of its children, this means its width directly corresponds to the specific <details> elements that are open.

For example, if just the first and third <details> are open, the inline-flex container will have the width 1px + 4px = 5px. Conversely, if the inline-flex container is 2px wide, we can infer that the only open <details> element is the second one. With this trick, we’ve managed to encode all eight states of the three <details> into the width of the container element.

This is pretty cool. Maybe we could use this as an element of some kind of puzzle game? We could show a secret message if the right combination of buttons is checked. But how do we do that? How do we only show the secret message for a specific width of that container div?

CodePen Embed Fallback

In the preceding CodePen, I’ve added a secret message as two nested divs. Currently, this message is always visible — complete with a TODO reminding us to implement the logic to hide it unless the correct combination is set.

You may wonder why we’re using two nested divs for such a simple message. This is because we’ll be hiding the message using a peculiar method: We will make the width of the parent div.secret be zero. Because the overflow: hidden property is used, the child div.message will be clipped, and thus invisible.

Now we’re ready to implement our secret message logic. Thanks to the fact that percentage sizes are relative to the parent, we can use 100% as a stand-in for the parent’s width. We can then construct a complicated CSS calc() formula that is 350px if the container div is our target size, and 0px otherwise. With that, our secret message will be visible only when the center button is active and the others are inactive. Give it a try!

CodePen Embed Fallback

This complicated calc() function that’s controlling the secret div’s width has the following graph:

Line chart showing the width of the secret div when the container div is at different widths.

You can see that it’s a piecewise linear curve, constructed from multiple pieces using min/max. These pieces are placed in just the right spots so that the function maxes out when the container div is 2px— which we’ve established is precisely when only the second button is active.

A surprising variety of games can be implemented using variations on this technique. Here is a tower of Hanoi game I had made that uses both width and height to track the game’s state.

SVG animation

So far, we’ve seen some basic functionality for implementing a game. But what if we want our games to look good? What if we want to add ✨animations?✨ Believe it or not, this is actually possible entirely within inline CSS using the power of SVG.

SVG (Scalable Vector Graphics) is an XML-based image format for storing vector images. It enjoys broad support on the web — you can use it in <img> elements or as the URL of a background-image property, among other things.

Like HTML, an SVG file is a collection of elements. For SVG, these elements are things like <rect><circle>, and <text>, to name a few. These elements can have all sorts of properties defined, such as fill color, stroke width, and font family.

A lesser-known feature of SVG is that it can contain <style> blocks for configuring the properties of these elements. In the example below, an SVG is used as the background for a div. Inside that SVG is a <style> block that sets the fillcolor of its <circle> to red.

CodePen Embed Fallback

An even lesser-known feature of SVG is that its styles can use media queries. The size used by those queries is the size of the div it is a background of.

In the following example, we have a resizable <div> with an SVG background. Inside this SVG is a media query which will change the fill color of its <circle> to blue when the width exceeds 100px. Grab the resize handle in its bottom right corner and drag until the circle turns blue.

CodePen Embed Fallback

Because resize handles don’t quite work on mobile, unfortunately, this and the next couple of CodePens are best experienced on desktop.

This is an extremely powerful technique. By mixing it with width-hacking, we could encode the state of a game or gizmo in the width of an SVG background image. This SVG can then show or hide specific elements depending on the corresponding game state via media queries.

But I promised you animations. So, how is that done? Turns out you can use CSS animations within SVGs. By using the CSS transition property, we can make the color of our circle smoothly transition from red to blue.

CodePen Embed Fallback

Amazing! But before you try this yourself, be sure to look at the source code carefully. You’ll notice that I’ve had to add a 1×1px, off-screen element with the ID #hack. This element has a very simple (and nearly unnoticeable) continuous animation applied. A “dummy animation” like this is necessary to get around some web browsers’ buggy detection of SVG animation. Without that hack, our transition property wouldn’t work consistently.

For the fun of it, let’s combine this tech with our previous secret message example. Instead of toggling the secret message’s width between the values of 0px and 350px, I’ve adjusted the calc formula so that the secret message div is normally 350px, and becomes 351px if the right combination is set.

Instead of HTML/CSS, the secret message is now just an SVG background with a <text> element that says “secret message.” Using media queries, we change the transform scale of this <text> to be zero unless the div is 351px. With the transition property applied, we get a smooth transition between these two states.

Click the center button to activate the secret message:

CodePen Embed Fallback

The first cohost user to discover the use of media queries within SVG backgrounds was @ticky for this post. I don’t recall who figured out they could animate, but I used the tech quite extensively for this quiz that tells you what kind of soil you’d like if you were a worm.

Wrapping up

And that’s will be all for now. There are a number of techniques I haven’t touched on — namely the fun antics one can get up to with the resize property. If you’d like to explore the world of CSS crimes further, I’d recommend this great linkdump by YellowAfterlife, or this video retrospective by rebane2001.


It will always hurt to describe Cohost in the past tense. It truly was a magical place, and I don’t think I’ll be able to properly convey what it was like to be there at its peak. The best I can do is share the hacks we came up with: the lost CSS tricks we invented while “posting, but better.”


The Lost CSS Tricks of Cohost.org originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

“Pretty” is in the eye of the beholder

Post pobrano z: “Pretty” is in the eye of the beholder

Hey, did you see the post Jen Simmons published about WebKit’s text-wrap: pretty implementation? It was added to Safari Technology Preview and can be tested now, as in, like, today. Slap this in a stylesheet and your paragraphs get a nice little makeover that improves the ragging, reduces hyphenation, eliminates typographic orphans at the end of the last line, and generally avoids large typographic rivers as a result. The first visual in the post tells the full story, showing how each of these is handled.

A screenshot of paragraph text that demonstrates a short last line, bad rag, bad hyphenation, and a typographic river.
Credit: WebKit Blog

That’s a lot of heavy lifting for a single value! And according to Jen, this is vastly different from Chromium’s implementation of the exact same feature.

According to an article by the Chrome team, Chromium only makes adjustments to the last four lines of a paragraph. It’s focused on preventing short last lines. It also adjusts hyphenation if consecutive hyphenated lines appear at the end of a paragraph.

Jen suggests that performance concerns are the reason for the difference. It does sound like the pretty value does a lot of work, and you might imagine that would have a cumulative effect when we’re talking about long-form content where we’re handling hundreds, if not thousands, of lines of text. If it sounds like Safari cares less about performance, that’s not the case, as their approach is capable of handling the load.

One thing to know as a developer, the performance of text-wrap is not affected by how many elements on the page it’s applied to. Perf concerns emerge as the pretty algorithm takes more and more lines into consideration as it calculates what to do. In WebKit-based browsers or apps, your text element would need to be many hundreds or thousands of lines long to see a performance hit — and that kind of content is unusual on the web. If your content is broken up into typical-length paragraphs, then you have no reason to worry. Use text-wrap: pretty as much as you want, and rely on our browser engineers to ensure your users will not experience any downsides.

Great, carry on! But now you know that two major browsers have competing implementations of the same feature. I’ve been unclear on the terminology of pretty since it was specced, and now it truly seems that what is considered “pretty” really is in the eye of the beholder. And if you’re hoping to choose a side, don’t, because the specification is intentionally unopinionated in this situation, as it says (emphasis added):

The user agent may among other things attempt to avoid excessively short last lines… but it should also improve the layout in additional ways. The precise set of improvements is user agent dependent, and may include things such as: reducing the variation in length between lines; avoiding typographic rivers; prioritizing different classes of soft wrap opportunities, hyphenation opportunities, or justification opportunities; avoiding hyphenation on too many consecutive lines.

So, there you have it. One new feature. Two different approaches. Enjoy your new typographic powers. 💪


“Pretty” is in the eye of the beholder originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

So, You Want to Give Up CSS Pre- and Post-Processors…

Post pobrano z: So, You Want to Give Up CSS Pre- and Post-Processors…

There was once upon a time when native CSS lacked many essential features, leaving developers to come up with all sorts of ways to make CSS easier to write over the years.

These ways can mostly be categorized into two groups:

  1. Pre-processors
  2. Post-processors

Pre-processors include tools like Sass, Less, and Stylus. Like what the category’s name suggests, these tools let you write CSS in their syntax before compiling your code into valid CSS.

Post-processors work the other way — you write non-valid CSS syntax into a CSS file, then post-processors will change those values into valid CSS.

There are two major post-processors today:

  • PostCSS
  • LightningCSS

PostCSS is the largest kid on the block while Lightning CSS is a new and noteworthy one. We’ll talk about them both in a bit.

I think post-processors have won the compiling game

Post-processors have always been on the verge of winning since PostCSS has always been a necessary tool in the toolchain.

The most obvious (and most useful) PostCSS plugin for a long time is Autoprefixer — it creates vendor prefixes for you so you don’t have to deal with them.

/* Input */
.selector {
  transform: /* ... */; 
}

.selector {
  -webkit-transform: /* ... */;
  transform: /* ... */;
}

Arguably, we don’t need Autoprefixer much today because browsers are more interopable, but nobody wants to go without Autoprefixer because it eliminates our worries about vendor prefixing.

What has really tilted the balance towards post-processors includes:

  1. Native CSS gaining essential features
  2. Tailwind removing support for pre-processors
  3. Lightning CSS

Let me expand on each of these.

Native CSS gaining essential features

CSS pre-processors existed in the first place because native CSS lacked features that were critical for most developers, including:

  • CSS variables
  • Nesting capabilities
  • Allowing users to break CSS into multiple files without additional fetch requests
  • Conditionals like if and for
  • Mixins and functions

Native CSS has progressed a lot over the years. It has gained great browser support for the first two features:

  • CSS Variables
  • Nesting

With just these two features, I suspect a majority of CSS users won’t even need to fire up pre-processors or post-processors. What’s more, The if() function is coming to CSS in the future too.

But, for the rest of us who needs to make maintenance and loading performance a priority, we still need the third feature — the ability to break CSS into multiple files. This can be done with Sass’s use feature or PostCSS’s import feature (provided by the postcss-import plugin).

PostCSS also contains plugins that can help you create conditionals, mixins, and functions should you need them.

Although, from my experience, mixins can be better replaced with Tailwind’s @apply feature.

This brings us to Tailwind.

Tailwind removing support for pre-processors

Tailwind 4 has officially removed support for pre-processors. From Tailwind’s documentation:

Tailwind CSS v4.0 is a full-featured CSS build tool designed for a specific workflow, and is not designed to be used with CSS pre-processors like Sass, Less, or Stylus. Think of Tailwind CSS itself as your pre-processor — you shouldn’t use Tailwind with Sass for the same reason you wouldn’t use Sass with Stylus. Since Tailwind is designed for modern browsers, you actually don’t need a pre-processor for things like nesting or variables, and Tailwind itself will do things like bundle your imports and add vendor prefixes.

If you included Tailwind 4 via its most direct installation method, you won’t be able to use pre-processors with Tailwind.

@import `tailwindcss`

That’s because this one import statement makes Tailwind incompatible with Sass, Less, and Stylus.

But, (fortunately), Sass lets you import CSS files if the imported file contains the .css extension. So, if you wish to use Tailwind with Sass, you can. But it’s just going to be a little bit wordier.

@layer theme, base, components, utilities;

@import "tailwindcss/theme.css" layer(theme);
@import "tailwindcss/preflight.css" layer(base);
@import "tailwindcss/utilities.css" layer(utilities);

Personally, I dislike Tailwind’s preflight styles so I exclude them from my files.

@layer theme, base, components, utilities;
@import 'tailwindcss/theme.css' layer(theme);
@import 'tailwindcss/utilities.css' layer(utilities);

Either way, many people won’t know you can continue to use pre-processors with Tailwind. Because of this, I suspect pre-processors will get less popular as Tailwind gains more momentum.

Now, beneath Tailwind is a CSS post-processor called Lightning CSS, so this brings us to talking about that.

Lightning CSS

Lightning CSS is a post-processor can do many things that a modern developer needs — so it replaces most of the PostCSS tool chain including:

Besides having a decent set of built-in features, it wins over PostCSS because it’s incredibly fast.

Lightning CSS is over 100 times faster than comparable JavaScript-based tools. It can minify over 2.7 million lines of code per second on a single thread.

Comparing build times for CSS Nano (544 milliseconds), ES Build (17 milliseconds), and Lightning CSS (4 milliseconds).

Speed helps Lightning CSS win since many developers are speed junkies who don’t mind switching tools to achieve reduced compile times. But, Lightning CSS also wins because it has great distribution.

It can be used directly as a Vite plugin (that many frameworks support). Ryan Trimble has a step-by-step article on setting it up with Vite if you need help.

// vite.config.mjs
export default {
  css: {
    transformer: 'lightningcss'
  },
  build: {
    cssMinify: 'lightningcss'
  }
};

If you need other PostCSS plugins, you can also include that as part of the PostCSS tool chain.

// postcss.config.js
// Import other plugins...
import lightning from 'postcss-lightningcss'

export default {
  plugins: [lightning, /* Other plugins */],
}

Many well-known developers have switched to Lightning CSS and didn’t look back. Chris Coyier says he’ll use a “super basic CSS processing setup” so you can be assured that you are probably not stepping in any toes if you wish to switch to Lightning, too.

If you wanna ditch pre-processors today

You’ll need to check the features you need. Native CSS is enough for you if you need:

  • CSS Variables
  • Nesting capabilities

Lightning CSS is enough for you if you need:

  • CSS Variables
  • Nesting capabilities
  • import statements to break CSS into multiple files

Tailwind (with @apply) is enough for you if you need:

  • all of the above
  • Mixins

If you still need conditionals like if, for and other functions, it’s still best to stick with Sass for now. (I’ve tried and encountered interoperability issues between postcss-for and Lightning CSS that I shall not go into details here).

That’s all I want to share with you today. I hope it helps you if you have been thinking about your CSS toolchain.


So, You Want to Give Up CSS Pre- and Post-Processors… originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Anchor Positioning Just Don’t Care About Source Order

Post pobrano z: Anchor Positioning Just Don’t Care About Source Order

Ten divs walk into a bar:

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>

There’s not enough chairs for them to all sit at the bar, so you need the tenth div to sit on the lap of one of the other divs, say the second one. We can visually cover the second div with the tenth div but have to make sure they are sitting next to each other in the HTML as well. The order matters.

<div>1</div>
<div>2</div>
<div>10</div><!-- Sitting next to Div #2-->
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>

The tenth div needs to sit on the second div’s lap rather than next to it. So, perhaps we redefine the relationship between them and make this a parent-child sorta thing.

<div>1</div>
<div class="parent">
  2
  <div class="child">10</div><!-- Sitting in Div #2's lap-->
</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>

Now we can do a little tricky positioning dance to contain the tenth div inside the second div in the CSS:

.parent {
  position: relative; /* Contains Div #10 */
}

.child {
  position: absolute;
}

We can inset the child’s position so it is pinned to the parent’s top-left edge:

.child {
  position: absolute;
  inset-block-start: 0;
  inset-inline-start: 0;
}

And we can set the child’s width to 100% of the parent’s size so that it is fully covering the parent’s lap and completely obscuring it.

.child {
  position: absolute;
  inset-block-start: 0;
  inset-inline-start: 0;
  width: 100%;
}

Cool, it works!

CodePen Embed Fallback

Anchor positioning simplifies this process a heckuva lot because it just doesn’t care where the tenth div is in the HTML. Instead, we can work with our initial markup containing 10 individuals exactly as they entered the bar. You’re going to want to follow along in the latest version of Chrome since anchor positioning is only supported there by default at the time I’m writing this.

<div>1</div>
<div class="parent">2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div class="child">10</div>

Instead, we define the second div as an anchor element using the anchor-name property. I’m going to continue using the .parent and .child classes to keep things clear.

.parent {
  anchor-name: --anchor; /* this can be any name formatted as a dashed ident */
}

Then we connect the child to the parent by way of the position-anchor property:

.child {
  position-anchor: --anchor; /* has to match the `anchor-name` */
}

The last thing we have to do is position the child so that it covers the parent’s lap. We have the position-area property that allows us to center the element over the parent:

.child {
  position-anchor: --anchor;
  position-area: center;
}

If we want to completely cover the parent’s lap, we can set the child’s size to match that of the parent using the anchor-size() function:

.child {
  position-anchor: --anchor;
  position-area: center;
  width: anchor-size(width);
}
CodePen Embed Fallback

No punchline — just one of the things that makes anchor positioning something I’m so excited about. The fact that it eschews HTML source order is so CSS-y because it’s another separation of concerns between content and presentation.


Anchor Positioning Just Don’t Care About Source Order originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.