How to keep wrapped flex-items the same width as the elements on the previous row?

前端 未结 13 1204
一整个雨季
一整个雨季 2020-11-29 01:24

I have a

    that is a flex-box and a bunch of
  • s in it which are the flex-items.

    I am trying to get the

13条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 01:48

    My solution is not ideal, as it leans on JQuery: http://codepen.io/BigWillie/pen/WwyEXX

    CSS

    ul {
      display: flex;
      flex-wrap: wrap;
    }
    
    li {
      min-width: 40px;
      max-width: 100px;
      flex: 1;
    }
    

    JavaScript

    var eqRowFlexItem = function(elem) {
        var w;
        var $elem = $(elem);
        // Clear out max-width on elements
        $elem.css('max-width', '');
        w = $(elem).eq(0).width();
        $(elem).css('max-width', w);
    }
    
    eqRowFlexItem('li');
    
    $(window).resize(function() {
        eqRowFlexItem('li');
    });
    

    I'm not entirely sure if it answers the problem. I found this post, as the title matched the problem I was having. I was after an effect whereby I would have a greater number of elements per row on larger screens - and fewer elements per row on smaller screens. In both cases, these elements also needed to scale to fit... across devices.

    However, those stray elements on the last row would always expand to fill the remaining space.

    The JQuery gets the width of the first element - and applies it as a max-width to every element. The OP wanted the blocks to fall within a min-width / max-width rage. Setting the max-width in CSS seems to work. We clear the max-width off the element, so it defaults to the max-width in the CSS... then gets the actual width.

提交回复
热议问题