Left align children in a centered dynamic width parent

后端 未结 3 1530
旧时难觅i
旧时难觅i 2021-01-20 15:11

I kinda can\'t wrap my head around it and it is also hard to find the proper solution on the web/here as it is hard to formulate.

Basically what I want is something

3条回答
  •  有刺的猬
    2021-01-20 15:36

    I don't know if this is the correct way to close this question, but I would want to thank everybody responding to my question. So I guess it is not possible to create this behavior only with CSS. jQuery or Media Queries are needed to get the proper behavior.

    Here is how I finally resolved the issue (using jQuery actually): http://jsfiddle.net/Ewtx2/

    HTML

    CSS

    #container {
        width:100%;
        text-align:center;
        border: 1px red dashed;
    }
    #outline {
        text-align: left;
        font-size:0;
        display: inline-block;
        padding-left:5px;
        padding-bottom:5px;
        /* for ie6/7: */
        *display: inline;
        border: 1px black dashed;
        zoom:1;
    }
    .innerbox {
        display:inline-block;
        height:50px;
        margin-top:5px;
        margin-right:5px;
        width:50px;
        background:red;
    }
    

    jQuery

    var boxAmount = 0;
    var newWidth = 0;
    setNewWidth();
    
    $(window).resize(function() {
        setNewWidth();
    });
    
    function setNewWidth() {
        // get container width and check how many boxes fit into it (account margin/padding)
        boxAmount = ($('#container').width() - 5) / ($('.innerbox').width() + 5);
        boxAmount = Math.floor(boxAmount);
        // multiply the box amount with the box width to get the new width to hold the box amount + padding
        if(boxAmount <= $('.innerbox').length) { 
            newWidth = boxAmount * $('.innerbox').width() + boxAmount * 5; 
        }
        // set the new calculated width
        $('#outline').width(newWidth);    
    }
    

    I wrote a script that takes the container width, divides it by the size of a single box, floors it, which gives us the amount of boxes fitting into the container. Then it multiplies this box amount with the box width, which then gives us the new size for the outline. The new size is set to the outline and thus the outline with all the boxes always stays centered and no strange white space to the right appears.

提交回复
热议问题