September 18, 2012

How to stack up a list of divs so there's no vertical gap?

Question by Prabhu

If I have a list (ul/li) of divs (with variable height), is there a way to stack them so that there are no gaps between a div and the div below it? Like the pinterest UI…

    <ul>
         <li>
           <div>...</div>
         </li>
         <li>
           <div>...</div>
         </li>
         ...
    </ul>    

    ul
    {
       list-style-type:none; 
       vertical-align:top;
    }

    li
    {
       list-style:none;    
       vertical-align:top;  
       display:inline-block;   
    }

This is similar to the question here How to make div stack first vertically then horizontally? except that I still want to order it like this:

1 2 3
4 5

Answer by Starx

Following CSS is enough to create that effect

ul, li  { margin: 0; padding: 0 }
ul li { float: left; }
ul li div { background: #f00; color: #fff; }

Demo

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!