javascript —

Modern CSS Might Make Your Front-End More Complex

Have you ever replaced fifty lines of JavaScript with a few lines of CSS, merged the PR, and felt like you just did the codebase a favor?

Modern CSS Might Make Your Front-End More Complex

You replace ResizeObserver with a container query, the diff is mostly red, and everyone approves it before lunch. This was what it looked like before you made the change: - The selector matches more than we meant. The :has(img) rule matches any descendant image, so the comment’s avatar counted as a hero image.

And the p element selector matches any descendant paragraph. As a result, the comment’s text was caught in the selection. - The selector outweighed the comment’s own rule. MDN’s specificity guide explains that :has() adds no weight by itself, but its argument does.

That gives .card:has(img) p a specificity score of 0-1-2, while .comment p comes in at just 0-1-1 and loses the battle. It could get even more complex and difficult to catch because the state changes at runtime. Let’s say a user posts a comment that includes an avatar.

The body text of the card above it loses its spacing. Good luck reproducing that from a bug report that says “spacing looks off sometimes.”

Earlier coverage

javascriptcloud

Related coverage

Elsewhere in this edition