简体   繁体   中英

CSS Target Last Paragraph After Heading

I've been looking how to edit the last paragraph after a heading using CSS.

I thought #div h1 ~ p:last-child would do the trick, but it skips down past the second heading and edits the last paragraph before the list. I've been searching for awhile and came across a few advanced css help sites, but they're repeating themselves with the most common advanced selectors.

The HTML:

<h1>Heading</h1>
<p>content</p>
<p>content</p>
<p>content</p>

<h2>Heading</h2>
<p>content</p>
<ul>
      <li>list</li>
      <li>list</li>
</ul>

The CSS:

#contentContainer > h1 ~ p:last-of-type {
    border-bottom: 1px solid #000;
}

The tilde character represents the general sibling selector:

The general sibling combinator selector is very similar to the adjacent sibling combinator selector The difference is that that the element being selected doesn't need immediately succeed the first element, but can appear anywhere after it.

This means it it could be after 100 different tags (eg h2, h3, div, img etc) and the css will still affect that.

As far as I am aware, there is no selector, or combination of selectors that will be able to do what you are trying to do, as the elements are all on the same level, and CSS doesn't get as advanced as "do this before it hits a different element".

Sorry - if I am wrong, which I hope I am for your sake.

If you only want to create a space between heading and last paragraph you can use

p + h2, p + h3 { 
    padding-top: 20px 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM