Flexbox works in Internet explorer but does not in

2019-08-07 00:52发布

问题:

What I would like to achieve: JSFiddle

<div id="container">
    <div class="box">1</div>
    <div class="box">2</div>
    <div class="box">3</div>
    <div class="box">4</div>
    <div class="box">5</div>
    <div class="box">6</div>
    <div class="box">7</div>
    <div class="box">8</div>
    <div class="box">9</div>
    <div class="box">10</div>
    <div class="box">11</div>
    <div class="box">12</div>
    <div class="box">13</div>
</div>

What I would like to have is that the 'X' amount of "box" classes fit in and make the "content" class wider when more "box" classes are placed.

In Internet Explorer(11) you see that the "box" class fit in the "content" class and expands it, but in Chrome(41) the "box" classes seem to float above the "content" class and outside the "content" class width. This is annoying because if I wand to place another "content" class next to it, it will overlap the first one.

Can anyone explain what i'm doing wrong? If it is a Chrome glitch any suggestions to accomplish this without flexbox?

Solved: Check other topic for multiple containers!

回答1:

First I'll suggest you to not mix float: left; with display: flex;. Consider specifying display: inline-flex; instead.

That said, I'm afraid you have to do a little computation, to find the biggest offset right (including margins) of all the children inside the container element :

The following piece of code requires jQuery, and is supposed to run when the DOM is ready :

// -----------------------------------------------------------------------------
// Find the biggest offset right among all children, relatively to the container
// -----------------------------------------------------------------------------

var maxOffsetRight = 0,
    currentOffsetRight;

$('#container').children().each(function() {
   currentOffsetRight = $(this).position().left + $(this).outerWidth(true);
    if (currentOffsetRight > maxOffsetRight) {
        maxOffsetRight = currentOffsetRight;
    }
});

// Set the width of the container
var offsetLeft = $('#container').position().left;
$('#container').css('width', maxOffsetRight - offsetLeft);

See fiddle

Note: You might think of an algorithm that looks for the offset right of the last child. That would work in most cases, but that could fail as well as you can set a property order on the flex items, to reorder them. Therefore the last child in the DOM is not necessarily the one that has the biggest right offset. That could also fail without reordering elements, if the children have arbitrary width. For example if the child before the last, in the same column, is larger than the last.