Search code examples
htmlcss

How to spread dynamic divs vertically, evenly?


Basically, i want the child divs to spread out evenly in the parent div, and if, one of the child divs is removed, the rest should resize and to fill the remaining space evenly again.

Ex:

 ---parent---------------
|  --------------------  |
| |              child | |
|  --------------------  |
|  --------------------  |
| |              child | |
|  --------------------  |
|  --------------------  |
| |              child | |
|  --------------------  |
 ------------------------   

now when a child div is remove, it should become

 ---parent---------------
|  --------------------  |
| |              child | |
| |                    | |
| |                    | |
|  --------------------  |
|  --------------------  |
| |              child | |
| |                    | |
| |                    | |
|  --------------------  |
 ------------------------   

Now, i want to do this with only pure html/css, but at the moment i can't find a solution.

The two other alternatives i am considering are to:

  • calculate the heights using javascript
  • create different classes for a bunch of scenarios (eg: a parent with 2 child divs, 3 child divs, 4 child divs, etc) and then load them accordingly with php

Anyone got a better idea ?


Solution

  • Use css tables with table-layout: fixed - no javascript is necessary.

    FIDDLE

    To see this working click 'inspect element' on one of the li elements of the above fiddle, then right-click 'delete node' and voila! - exactly what you need.

    Markup

    <ul>
        <li><span>Item1</span></li>
        <li><span>Item1</span></li>
        <li><span>Item1</span></li>
        <li><span>Item1</span></li>
    </ul>
    

    CSS

    ul
    {
        display: table;
        table-layout: fixed;
        width: 100%;
        border: 1px solid #c2c2c2;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
    }
    
    li
    {
        text-align: center;
        display: table-row;
        background: pink;
    }
    span
    {
        display: table-cell;
        vertical-align: middle;
        border-top: 1px solid green;
    }