skip to Main Content

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

.test < p
.test + p

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

2

Answers


  1. Chosen as BEST ANSWER

    It was easier then I thought:

    div:has(.test) {
       p {...}
    }
    

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

    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 */
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search