April 25, 2012

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

Question by rob

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.

Answer by Starx

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;
}

Answer by Starx

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;
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!