Search code examples
csswidth

Switching from 3 columns to 2


I have a responsive layout set up for 3 columns. In each column is a product that we are trying to sell. Sometimes there could be 3 items, 2 items and 1 item. Currently when I remove 1 item it will display on 2/3 of the page and leave the 1/3 empty. How do I create it so that when there are 2 or 1 item being displayed for them to be centered and they would have a max-width of 640px?

/* -------- HTML ------------*/ 

<div class="item">Item1</div>
<div class="item">Item1</div>
<div class="item">Item1</div>

/* -------- CSS ------------*/ 

.item {
display: inline;
float: left;
width: 33.33%;
}

Solution

  • With flexbox, the container will fill 100% of the space based on how many items you have.

    HTML

    <div class="flex-row">
      <div class="item">Item1</div>
      <div class="item">Item2</div>
      <div class="item">Item3</div>
    </div>
    
    <div class="flex-row">
      <div class="item">Item1</div>
      <div class="item">Item2</div>
    </div>
    
    <div class="flex-row">
      <div class="item">Item1</div>
    </div>
    

    CSS

    .flex-row {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
    }
    .item {
      flex: 1;
    }
    

    Here is an example