Search code examples
htmlcsscss-selectorspseudo-class

CSS ":is()" pseudo-class with relative selectors


I want to style specific "sections that are directly inside the body" and "sections that are directly inside a div directly inside the body" with the ":is()" pseudo-class, without the redundancy (with relative selectors).
I have the following code in a index.html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css">
    <title>Test :is() Selector</title>
  </head>
  <body>
    <section>Section directly inside the body (styled).</section>
    <div>
      <section>Section directly inside a div which is directly inside the body (styled).</section>
    </div>
    <div>
      <div>
        <section>Section directly inside a div which is directly inside another div which is directly inside the body (not styled).</section>
      </div>
    </div>
  </body>
</html>

and the following CSS in a style.css file:

body > :is(section, div > section) {
  background-color: lightblue;
  padding: 10px;
  border: 1px solid blue;
}

I tried searching about, but I was unsuccessful because all searches with the ":is()" pseudo-class and relative selectors send me straight to the relative selectors documentation, since "is" is a very common word without special characters. This is my first question in stack (although I read this site every day for a long time), but what I need is some complex selector without redundancy that would have the same result as this CSS:

body > section, body > div > section {
  background-color: lightblue;
  padding: 10px;
  border: 1px solid blue;
}

Solution

  • You can use & and :is() like below:

    body {
       :is(&, & > div) > section {
        background-color: lightblue;
        padding: 10px;
        border: 1px solid blue;
      }
    }
    <section>Section directly inside the body (styled).</section>
    <div>
      <section>Section directly inside a div wich is directly insdie the body (styled).</section>
    </div>
    <div>
      <div>
        <section>Section directly inside a div wich is directly inside another div which is directly inside the body (not styled).</section>
      </div>
    </div>