Say I have a bunch of P, LI, or DIV elements, with nothing between them. I want to control the vertical spacing between them, so they don\'t fit so tightly. But I don\'t want
p { margin: 10px 0 0 0; }
p:first-child { margin: 0; }
That is, set a top margin of 10px for all p
elements and other margins to zero, except for the first p
element, for which you set even the top margin to zero.
This works more widely than many other approaches, which use contextual selectors that are not supported by old browsers. To get really maximal browser support, you would assign a class to the first p
element in markup and use a class selector instead of p:first-child
.
This is the simplest possible way, since CSS operates on elements, not on what’s between elements. So you need some way of distinguishing the first p
element in a sequence of p
elements.
Note that p { margin: 5px 0; }
(mentioned in the question) would create vertical margins of 5px, not 10px, because adjacent vertical margins collapse.