Search code examples
csswidthparentchildrenexpand

Children div to expand to the full width size of the parent div with css on the same row


<style>
.classname {
    min-width:248px;
    height:40px;
    max-width:498px;
    border:1px solid red;
    float:left;     
}
</style>

    <div id="maindiv" style="width:3134px;border:1px solid green;height:90px;">
        <div class="classname">
        </div>
        <div class="classname">
        </div>
        <div class="classname">
        </div>
    </div>

So no matter how many children the maindiv has I whant them to expand to the fullsize of the parent width size. Ex: If maindiv has 1200px width the children to have 400px each if are 3 or 300px if are 4 ONLY CSS SOLUTION


Solution

  • It's a little long-winded, but possible

    /* one item */
    .classname:first-child:nth-last-child(1) {
        width: 100%;
    }
    
    /* two items */
    .classname:first-child:nth-last-child(2),
    .classname:first-child:nth-last-child(2) ~ .classname {
        width: 50%;
    }
    
    /* three items */
    .classname:first-child:nth-last-child(3),
    .classname:first-child:nth-last-child(3) ~ .classname {
        width: 33.3333%;
    }
    
    /* four items */
    .classname:first-child:nth-last-child(4),
    .classname:first-child:nth-last-child(4) ~ .classname {
        width: 25%;
    }
    
    ...
    

    You will probably also need

    .classname {
        display: inline-block;
    }
    

    See Lea Verou's blog post for more details