Everytime there is a H2 followed by a UL, I must put those two properties, so I wanted to do a selector with h2 and ul
As stated by @Spudley and @Coop, you can't select an element that is followed by another element (except rare cases with series of li or td or th and :nth-last-child()
but it's more of a trick).
The closest thing you can do in pure CSS is testing if h2 is followed by (an)other element(s) or not, i.e. if it's not alone with :only-child
pseudo.
From MDN:
The :only-child
CSS pseudo-class represents any element which is the only child of its parent. This is the same as :first-child:last-child
or :nth-child(1):nth-last-child(1)
, but with a lower specificity.
Support is IE9+ so if you want to style this element in IE7 and IE8 too (or in the precise case where it's followed by ul but not p or h3...), you'll need JavaScript or to add a class server-side and style this class.
.ui-content > h2:not(:only-child) {
margin-top: 30px;
margin-bottom: -30px;
}
EDIT:
You can also test if H2 is both the :first-child
and the second-to-last child of its parent so it'll be styled if it's followed by whatever element but not if this second element has other siblings (third, fourth one, etc)
.ui-content > h2:first-child:nth-last-of-type(2) {
margin-top: 30px;
margin-bottom: -30px;
}
Simplest code would be ;)
<div class="ui-content">
<h2 class="followed-by-list">Text</h2>
<ul class="ui-listview">
List Items
</ul>
</div>
.followed-by-list {
margin-top: 30px;
margin-bottom: -30px;
}
Other trick that'd mean a complete overhaul of your project (say, for next project ;) ): never set a single margin-bottom
to content elements (I mean h2, ul, p, etc. It's OK for div and below "blocks") and always set a margin-top to:
- an element (general case) ex: p
- if needed, an element coming after another like
elt1 + p
would have a certain margin-top, elt2 + p
another one, etc