Clever CSS Selectors
This little aide memoire came from the need to set up a list of headings (h2) with images and text and separate them from each other - but I didn't want a separator line above the first h2/text/image section because that would separate it from the main heading (h1). See the box below for an example
Fancy Selectors in CSS
The requirement
Have headings with text and separate them with a divider the previous heading/text combination but...
This is another heading
.. no divider above the first heading.
And a third heading
In this little example, there's no styling in the markup, like this:
<h2 style="border-top:1px solid #666;" >
<h2 class="addline">
The Answer
Use Adjacent Sibling Selector, p + h2 {border-top:1px solid #666; which says only set the top border of a h2 that immediately follows a p.
Here are some clever CSS Selectors
- Adjacent Sibling
- div.aaa div.bbb + div.bbb { ... }
- Pseudo-Class
- div.aaa div.bbb:firstchild { ... }
- Child Selector
- div.aaa > div.bbb { ... }
What do the selectors select?
(Hover on yes/no for an explanation)