Distribute buttons as evenly as possible

后端 未结 2 1357
轮回少年
轮回少年 2021-02-08 05:56

I have a variable width container (a div).

This container contains a variable number of buttons whose sizes

2条回答
  •  长发绾君心
    2021-02-08 06:17

    As I told you, I think this is not achievable with CSS only (yet) :P

    Using some JS, this is the best solution I can think of:

    http://jsfiddle.net/1fz0djvL/

    var buttons = document.querySelector(".buttons");
    
    function distribute(){
        buttons.style.width = "auto";
        var height = buttons.offsetHeight;
        do{
            buttons.style.width = buttons.offsetWidth - 1 + "px";
            if(buttons.scrollWidth > buttons.offsetWidth) break;
        }
        while(buttons.offsetHeight == height);
        buttons.style.width = buttons.offsetWidth + 1 + "px";
    }
    distribute();
    window.addEventListener("resize", distribute);
    

    It shrinks the container as long it doesn't grow in height.

提交回复
热议问题