Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add vertical spacing between block elements, but not top and bottom

Tags:

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.

like image 732
rob Avatar asked Apr 25 '12 04:04

rob


People also ask

How do I make vertical spacing in CSS?

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.

How do you add a space between two elements?

To create extra spaces before, after, or in-between your text, use the &nbsp; (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.


1 Answers

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;
}
like image 100
Starx Avatar answered Sep 27 '22 19:09

Starx