Fjut
Fjut

Reputation: 1324

Overflow with flex-basis and min and max-width

My goal is to use flexbox to implement a slider that has a given width and can grow as items(images) are added into it, until a specific width is reached. After that width is reached i want to show a scrollbar on the x axis. I also want the slider not to shrink bellow the min-width.

This is what i tried:

HTML:

<div class="wrapper">
  <div class="thisDivAllowsSliderToGrowToMaxWidth">
    <div class="slider">
      <div class="image"></div>
      ...
    </div>
  </div>
</div>

CSS:

.wrapper {
  height: 400px;
  display: flex;
  justify-content: center;
  align-items:center
}

.slider {
  display:flex;
  justify-content:flex-start;
  height:100px;
  flex-basis: 250px;
  min-width:200px;
  max-width:350px;
  overflow-x:auto;
}

.image {
  flex-shrink:0;
  height:100px;
  width:50px;
}

The issue that pops out is that as soon as overflow-x is added to the slider, it does not grow anymore but shows the scrollbar as soon as flex-basis width is reached.

Interestingly, adding a simple wrapping div (.thisDivAllowsSliderToGrowToMaxWidth) around the slider somehow fixes the issue. You can find the example here.

Can anyone answer why is this happening and am I using the flex properties as intended?

Upvotes: 3

Views: 4286

Answers (1)

Tyler Fowle
Tyler Fowle

Reputation: 569

To make the flex container grow based on the width of the flex items, you can set the flex-basis to content

content will automatically size based on the flex item's content

$(".add-slide").on("click",function(){

$(".slider").append('<div class="image"></div>');

});
    .wrapper {
      height: 300px;
      border :1px solid red;
      display: flex;
      justify-content: center;
      align-items:center
    }

    .slider {
      display:flex;
      border: 1px solid black;
      height:100px;
      flex-basis: content;
      min-width:200px;
      max-width:350px;
      overflow-x:auto;
      overflow-y:hidden;
    }

    .image {
      flex-shrink: 0;
      border: 1px solid green;
      height:100px;
      width:50px;
    }

    button {
      margin-bottom: 20px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
<button class="add-slide">add slide</button>

<div class="wrapper">
    <div class="slider">
        <div class="image"></div>
    </div>
</div>
    
    

Upvotes: 3

Related Questions