2

I'm trying to understand why the following code does not creates a scrollable flexbox.

var firstData = ["One", "Two", "Three", "Four"]
FillDiv();
FillDiv();

$("button").on('click', function() {
 FillDiv();
});

function FillDiv() {
 var newData = GetData();
  
  for (i = 0; i < newData.length; i++) {
    $(".wrapper").append('<div>Test</div>');
  }
}

function GetData() {
  return firstData;
}
.wrapper {
  display: flex;
  overflow-x: auto;
}

.wrapper div {
    display: block;
    width: 200px;
    height: 200px;
    background-color: black;
    color: white;
    text-align: center;
    margin-left: 1%;
  }

button {
  margin-top: 20px;
  margin-left: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
</div>

<button>
NEXT
</button>

However, the following example does:

.container {
  display: flex;
  overflow-x: auto;
}
<div class="container">
<img src="https://as1.ftcdn.net/jpg/02/12/43/28/500_F_212432820_Zf6CaVMwOXFIylDOEDqNqzURaYa7CHHc.jpg" alt="">
<img src="https://as1.ftcdn.net/jpg/02/12/43/28/500_F_212432820_Zf6CaVMwOXFIylDOEDqNqzURaYa7CHHc.jpg" alt="">
<img src="https://as1.ftcdn.net/jpg/02/12/43/28/500_F_212432820_Zf6CaVMwOXFIylDOEDqNqzURaYa7CHHc.jpg" alt="">
<img src="https://as1.ftcdn.net/jpg/02/12/43/28/500_F_212432820_Zf6CaVMwOXFIylDOEDqNqzURaYa7CHHc.jpg" alt="">
<img src="https://as1.ftcdn.net/jpg/02/12/43/28/500_F_212432820_Zf6CaVMwOXFIylDOEDqNqzURaYa7CHHc.jpg" alt="">
<img src="https://as1.ftcdn.net/jpg/02/12/43/28/500_F_212432820_Zf6CaVMwOXFIylDOEDqNqzURaYa7CHHc.jpg" alt="">

</div>

Why does the scroll breaks when I add width and height in first example?

Bagzli
  • 6,254
  • 17
  • 80
  • 163

1 Answers1

1

Add flex-shrink: 0 to your Test divs. Flex items are set, by default, to flex-shrink: 1, which enable them to shrink in order to prevent an overflow of the container.

For more details see "The flex-shrink factor" section in my answer here:


The problem addressed above doesn't exist in your second example (with the images) because another default setting of flex items is min-width: auto. This means that flex items cannot, by default, be smaller than their content. If you override this default with img { min-width: 0 }, you'll get the same behavior as in your first example.

For more details about the flex minimum sizing algorithm see:

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701