Distribute buttons as evenly as possible

后端 未结 2 1356
轮回少年
轮回少年 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:13

    CSS doesn't contain enough 'math' powers (cross browser) to determine widths and available space. If they were similarly shaped, it would be easier to accomplish with a grid based system like bootstrap and media queries. But because 15 'G+' buttons fit in 2 'stackoverflow' space, it will never be the solution you want without determining element widths.

    I'd suggest resulting to the JS solution you came up with already.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题