Select specific element before other element

As far as I know, CSS doesn’t offer any selectors which will target before a selector. Could you select it as an h2 which is directly after a p (p + h2)?

h2 {
    color: #1a1a1a;
}

p + h2 {
    color: #0cc;
}

Example on JSFiddle

As you can see, this is probably the best selector you can use if you’re relying on CSS, although you could easily just add a class to each h2 that is before a ul. That would avoid the case where you have a paragraph section before another h2 and paragraph section.

You could do this using jQuery:

.highlight {
    color: #0cc;
}

$('ul').prev('h2').addClass('highlight')

Example on JSFiddle

This selects every ul, then selects the h2 that is before it, before finally adding the .highlight class to it.

Leave a Comment