• Reduce CSS Code with the :is Selector
  • By Bill Chen
  • The Nuggets translation Project
  • Permalink: Use the: IS selector to simplify your CSS code
  • Translator: Front-end picker
  • Proofreader: None (Your comments are welcome, you can spray me)

introduce

When writing CSS, we often use compound selectors when we want to add the same attributes to children of the same parent element, as shown in the figure below.

.container. Title,.container. Detail {color: black; }Copy the code

Compound selectors allow us to set the same CSS properties for multiple elements at the same time. However, if we have more children, we have to write the parent class repeatedly. The :is selector can be used to solve the problem of repeating parent elements.

For example,

Given the following HTML code.

<div class="card --card1">
  <h2 class="title">Normal CSS</h2>
  <p class="detail">
    .--card1 .title,
    .--card1 .detail {
      color: brown;
    }
  </p>
</div>
Copy the code

Suppose we want to brown both the h2 title and the detail element. Common practices are as follows:

/* Normal CSS */
.--card1 .title..--card1 .detail {
  color: brown;
}
Copy the code

The rendering looks like this:

Although the CSS code above worked, we wrote the parent element twice, creating redundancy. Let’s look at the effect of the is selector:

/* : is a selector */
.--card2 :is(.title..detail) {color: brown; }Copy the code

The: IS selector achieves the same effect as the repeat selector, and the code is more streamlined.

CSS FaQs

A common problem with both CSS and SCSS is that CSS selectors do not work as expected when errors occur in code.

Suppose there is a typo:. Detail incorrectly written as :detail

/* Normal CSS with errors */
.--card3 .title..--card3 :detail {
  color: brown;
}
Copy the code

The effect is as follows:

As you can see from the figure, not only does the detail element not display the desired color, but the title element does not display the correct color value. This is because the browser parses the whole block of code together and invalidates the entire selector when one bad code occurs.

Different results occur when a similar situation occurs with the: IS selector.

/* :is selector with errors */
.--card4 :is(.title, :detail) {
  color: brown;
}
Copy the code

As you can see, even if we get a typo when we try to write the detail element, the title element still shows the color as expected.

The source code for this tutorial can be found at CodePen:

“Codepen. IO/chen1223 / em…

Recommended reading

:is and: Where make your CSS simpler