Home > database >  Select element only when another element has a specific data attribute value
Select element only when another element has a specific data attribute value

Time:11-28

I have a <header> with the class .header and [data-header-style="Standard"].

Now I want the <main> element of my page to have a padding of 100px, but only if the header has [data-header-style="Standard"].

Is this possible without Javascript? Thank you for the help!

I know that I can select the header with [data-header-style="Standard"].header, but unfortunately not how to do it with <main>.

CodePudding user response:

I'm assuming your HTML looks something like this:

<header  data-header-style="Standard">
  ...
</header>

<main>
  ...
</main>

You need the CSS general sibling combinator (~), which you can use like this:

[data-header-style="Standard"].header ~ main {
  padding: 100px;
}

This selects all main elements that follow your header. In this case, it will select your main element and give it the 100px padding, but only if the header matches the first selector.

You can read more about the general sibling combinator on MDN. There's also an adjacent sibling combinator if you'll ever find that useful.

  • Related