Simplify your CSS code

2 min read · 10/26/22

CSS has been evolving faster and faster, and one of the most remarkable highlights is the new :is() and :where() selectors.

Compatible with modern browsers, these selectors significantly simplify CSS code, especially when dealing with complex or repetitive selectors. Both accept a list of selectors, targeting elements that match any listed selector.

Traditional vs Modern selector approaches

Consider this traditional CSS code:

ul li.title,
ol li.title {
  color: tomato;
}

And its Sass Preprocessor equivalent:

ul,
ol {
  li.title {
    color: tomato;
  }
}

Both compile to:

ul li.title,
ol li.title {
  color: tomato;
}

Now, using :is() and :where():

:is(ul, ol) li.title {
  color: tomato;
}

:where(ul, ol) li.title {
  color: tomato;
}

This streamlined approach enhances readability and efficiency.

Differences between the selectors

  • :is(): Simplifies nested selectors, similar to CSS preprocessors like Sass. However, it treats specificity differently. The specificity is the highest among the provided selectors.
  • :where(): Unique in its zero specificity, this selector won’t interfere with other CSS specificity rules, making it ideal for styling without specificity conflicts.

Why use these selectors?

  1. Simplification: Reduces the length and complexity of CSS selectors.
  2. Specificity Management: :where() offers a zero-specificity approach, a first in CSS.
  3. Library Integration: These selectors pave the way for CSS libraries with no specificity conflicts.

Incorporating these selectors into your CSS promises more readable, simpler, and conflict-free styling.

Connect

I try to keep it minimal.

Or reach me at me@luxonauta.com.