so-33590889

Alternative answer to stackoverflow question: when-centering-horizontally-lis-get-cut-off

by Rene van der Lende

HTML

<button onclick="addLI()">Add LI</button>
<button onclick="delLI()">del LI</button>
<span id="demo"></span>

<div>
    <ul id="myList">
    </ul>
</div>

CSS

/* *                     { outline: 1px dashed black } /* just for debugging */

        html, body              { box-sizing: border-box; height: 100%; width: auto;
                                  margin: 0; padding: 0; border: 0; cursor: default }

        *, *:before, *:after    { box-sizing: inherit }

        ul, li                  { list-style: none; margin: 0px; padding: 0px }

        body                    { max-width: 100%; max-height: 100%; margin: 0 auto; overflow: hidden;
                                  -webkit-user-select: none; -moz-user-select: none; 
                                      -ms-user-select: none;      user-select: none }

div {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    width: auto;
    background-color:aqua;
}

ul {
    display: inline-flex; flex-flow: column wrap;
    justify-content: center;
        align-items: center;
    align-content: center;
    width: 100%;
    height: 70%; margin-top: auto; margin-bottom: auto;
    overflow-x: auto;
}


li {
    display: inline;
    flex-basis: 200px;
    width: 200px;
    
    background-color: greenYellow;
    color: firebrick;
    border: 1px solid firebrick;
}

JavaScript

function addLI() {
    var parent = document.getElementById("myList");
    var li     = document.createElement("li");
    var items  = parent.querySelectorAll('li').length +1; /* get total, add 1 new */
    var cols   = parseInt(Math.ceil(items / 3));

    /*Workaround for improper update of parent.scrollwidth in FF and CH (webkit) */
    if (parent.style.alignContent = 'center') {
        if ( cols*200 > parent.scrollWidth ) 
        	parent.style.alignContent = 'flex-start';
    };
    parent.appendChild(li);

    /*demo*/
    document.getElementById("demo").innerHTML = 'current UL align-content: ' +  parent.style.alignContent;
    li.appendChild(document.createTextNode(items));
    /**/
}

function delLI() {
    var parent = document.getElementById("myList");
    var li     = parent.lastChild;
    var items  = parent.querySelectorAll('li').length-1;
    var cols   = parseInt(Math.ceil(items / 3));

    if (items >= 0) {
        parent.removeChild(li);   
       
        if ( cols*200 != parent.scrollWidth ) {
        	parent.style.alignContent = 'center';

        	/*demo*/
            document.getElementById("demo").innerHTML = 'current UL align-content: ' + parent.style.alignContent;
            /**/
        };
    };
}