Search code examples
htmlcssflexboxwidth

Why is the width property not being respected in the flexbox?


I have a flexbox and I want want it's items to have a width of 200px but it doesn't go over 500/5 = 100px.

I set the min-width to 200px and it worked, but I don't know why width didn't work. Could someone explain to me why it happened? I don't know much about flexbox (or anything in CS or CSS for that matter) so please go light on the technical jargon.

Thanks!

My code:

HTML

  <h3>width/height</h3>
    <div class="flex-container two">
        <div class="flex-item">Item</div>
        <div class="flex-item">Item</div>
        <div class="flex-item">Item</div>
        <div class="flex-item">Item</div>
        <div class="flex-item">Item</div>
    </div>

CSS

.flex-container {
    font-size:14px;
    display:flex;
    margin-bottom:2rem;
    width:500px;
}

.flex-container.two > .flex-item {
    width:200px;
}

Solution

  • you gave the parent a width of 500px and children of 200px, how can they fit? my suggestion is to set the parent's width to fit-content if you want children to have that exact width... and if you want them to overflow and have the exact width you gave them(200px) use flex-shrink: 0 ;

    .flex-container {
      font-size: 14px;
      display: flex;
      margin-bottom: 2rem;
      width: 500px;
    }
    
    .flex-container.two > .flex-item {
      flex-shrink: 0;
      width: 200px;
    }
    <h3>width/height</h3>
    <div class="flex-container two">
      <div class="flex-item">Item</div>
      <div class="flex-item">Item</div>
      <div class="flex-item">Item</div>
      <div class="flex-item">Item</div>
      <div class="flex-item">Item</div>
    </div>