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 to add any space top and bottom, since that is handled by the parent element and I don't need more. Is there a simple way to do this that works for all block elements?
Say I've got something like this :
p {
margin: 5px 0;
}
and then
<div>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</div>
But I don't want 5px above p 1, or below p 4, since the div already has padding and I don't want to go messing with that. I just want the 10px between p 1 and p 2, p 2 and p 3, etc.
I'm sure I could do something kludgy (and I have many times), but am looking for something cleaner that I don't have to do a lot of special-casing for this common situation.
Use the line-height property in CSS to do so. Browsers by default will create a certain amount of space between lines to ensure that the text is easily readable. For example, for 12-point type, a browser will place about 1 point of vertical space between lines.
To create extra spaces before, after, or in-between your text, use the (non-breaking space) extended HTML character. For example, with the phrasing "extra space" using a double space, we have the following code in our HTML.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With