Left align children in a centered dynamic width parent

后端 未结 3 1554
旧时难觅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:38

    I did it with pure CSS by adding a couple of container divs around the square elements and playing around with the displays and text-alignment. See a demo here

    HTML:

    CSS:

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

    Note based on comments below

    There is a space between the right most box and the right of its container when the boxes take up more than one line. Without some sort of javascript this small amount of space is impossible to remove completely

    Edit to add fully functionality using javascript

    Here is my attempt at achieving full functionality using javascript and jQuery: demo here. It's still glitching when shrinking the window size due to the added
    s, but I'll look for a fix and the code might be useful to some users in addition to your answer. I think my solution is slightly more generic than yours though. Glad I could help you get the right idea!

    Pure javascript version added later

    Here is my most recent version of this objective. It is in pure javascript, removes the need for a container, and removes the hard-coded padding values

提交回复
热议问题