htmlcsswidth

CSS Make last child to dynamically take width which left in parent


In my case childs number is returned from server side. In case there are less than 6 childs I need to add dummy child which would take left place of parent.

For example :

1 situation with two childs enter image description here 2 situation with three childs enter image description here

fiddle

<div id="container">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="big-child"></div>
</div>
#container{
    width: 100%;
    height: 200px;
    background-color: gray;
}

#container > div {
    float: left;
    background-color: black;
    width: 100px;
    height: 100px;
    margin-right: 20px;
}

.big-child {
    width: 59%!important;
    margin-right: 0px!important;
}

How could I achieve this with only CSS and withoud dinamically changing child width with javascript?

UPDATE

Found good website which generates CSS code depending on your boxes needs.


Solution

  • You could use a flexbox container and set flex-grow: 1 to the last child of its parent (so you don't even need to apply a different class name to the last child)

    Since you need to have a dummy element only for less than 6 children you may change the behavior of the last element by checking if :last-child is not at the same time :nth-child(n + 6)

    #container{
        --gap: 20px;
        --size: min(12vw, 100px);
        
        display: flex;
        gap: var(--gap);
        margin-block: 2rem 0;
        block-size: 200px;
        background-color: gray;
    
        > div {
           background-color: black;
           inline-size: var(--size);
           block-size: var(--size);
        }
        
        > :last-child:not(:nth-child(n + 6)) {
          flex-grow: 1;
          margin-inline-end: var(--gap); /* if you need the gap at the end */
        }
    }
    <div id="container">
        <div class="child">1</div>
        <div class="child">2</div>
        <div class="child">3</div>
    </div>
    
    
    <div id="container">
        <div class="child">1</div>
        <div class="child">2</div>
        <div class="child">3</div>
        <div class="child">4</div>
    </div>
    
    
    <div id="container">
        <div class="child">1</div>
        <div class="child">2</div>
        <div class="child">3</div>
        <div class="child">4</div>
        <div class="child">5</div>
    </div>
    
    
    <div id="container">
        <div class="child">1</div>
        <div class="child">2</div>
        <div class="child">3</div>
        <div class="child">4</div>
        <div class="child">5</div>
        <div class="child">6</div>
    </div>


    Further readings: http://css-tricks.com/snippets/css/a-guide-to-flexbox/