Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 342
Alina Avatar asked Sep 23 '12 21:09

Alina


People also ask

How do you target the last paragraph in CSS?

The :last-of-type selector allows you to target the last occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content. ).

How do I write paragraph next to heading in HTML?

In our HTML we have a <h1> followed by a <p> . The <p> is an adjacent sibling of the <h1> so we can select it with h1 + p .

How do I get the last element in CSS?

The :last-of-type CSS pseudo-class represents the last element of its type among a group of sibling elements.


2 Answers

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 (e.g. 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.

like image 114
David Avatar answered Nov 15 '22 05:11

David


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

p + h2, p + h3 { 
    padding-top: 20px 
} 
like image 40
user3751934 Avatar answered Nov 15 '22 05:11

user3751934