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
Use adjacent selectors
p + p { margin-top: 10px; }
Basically the concept is that, if a p
comes after another p
give 10px margin in between.
You usage is something similar to
p + p, li + li, div + div {
margin-top: 10px;
}
This can also be done using :last-child
or :first-child
Here is an example:
p, li, div {
margin-bottom: 10px;
}
p:last-child, li:last-child, div:last-child {
margin-bottom: none;
}
You can use adjacent selectors. You can define like this:
p + p{
margin-top:0;
}
OR
p ~ p{
margin-top:0;
}
p, li, div {
margin-bottom: 10px;
}
#parentID {
margin-bottom: -10px;
}
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.