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

HTML/CSS – Select child directly after h2-element?

For example, I have following short html-code:

<div ...>
  <h2 class="test">...</h2>
  <p>...</p>
</div>

Is it somehow possible to get the child-element (p in this example) after the h2?

Thought of something like

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

.test < p
.test + p

(For my specific topic/task I have to "select" the child after h2 like, if that is even possible.)

>Solution :

In CSS, you can use the adjacent sibling combinator (+) to select an element that is immediately preceded by another specific element.

However, you can’t select an element that is a child of another element directly with just CSS. CSS is designed to style elements based on their relationship to their parent, not to select and style elements based on their relationship to sibling elements.

So, in your example, if you want to style the <p> element that comes directly after the <h2> element with the class "test", you can use the adjacent sibling combinator like this:

h2.test + p {
  /* Your CSS styles for the <p> element here */
}
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