Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select element only when another element has a specific data attribute value

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

I’m assuming your HTML looks something like this:

<header class="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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading