Typesetting a community school homepage

There is an instruction in this project saying:

Give the first paragraph after each heading in the a little bit of text-indentation, say 20px.

I read the finished code and saw this is done with

section h2 + p { 
    text-indent: 20px;
}

This works for the provided html context specifically (you can check the live example here) but I actually struggled while working on this part because I want this code to work more generally, say, even when there is some other tags getting in between h2 and and the first p after h2. In other words, in such scenarios:

  <section>
      <h2>Example heading</h2>

      <div>interrupting div</div>

      <p>Example paragraph 1.</p>

      <p>Example paragraph 2.</p>

      <h2>Example heading</h2>

      <div>interrupting div</div>

      <p>Example paragraph 3.</p>

      <p>Example paragraph 4.</p>

      <ul>
        <li>Emotional control</li>
        <li>Judgement</li>
        <li>Assertion</li>
        <li>Focus and resolve</li>
      </ul>

      <p>Example paragraph 5.</p>
      
      <ol>
        <li><a href="#">Call us</a> for more information</li>
        <li><a href="#">Ask for a brochure</a>, which includes signup form</li>
        <li><a href="#">Book a visit</a>!</li>
      </ol>
  </section>

The Example paragraph 1 and Example paragraph 3 should still be indented, but other paragraphs should not be indented.

I tried selectors like h2 ~ p:first-of-type but it only works for Example paragraph 1.

I modified and uploaded the finished code with interrupting div tag to JsBin (font-family isn’t applied but since it’s irrelevant to my question please just ignore), you can try it on the fly if you find this question interesting too. Let me know if you have any idea, thanks!

The problem here is that inside the <section> container, the p:first-of-type is the one that begins with “It’s a brave new world out there…”, so it’s the only one that will have the indentation applied.

The other p elements, although related with the h2 elements with the precedence operator ~ are not the first of their type inside the container.

You’d need a more complex selector to make it work with the interrupting div, but instead I’d rather rethink the page structure to present the information in a different way.

1 Like

I agree with @dsthode that this would be a moment to think about the general structure. If there is an arbitrary optional single element in between you could use this selector:

section h2 + p,
section h2 + *:not(p) + p { 
    text-indent: 20px;
}

Of course this would fail for two interrupting elements (but could be expanded to also match two)