Search code examples
htmlcssresponsive-designgrid-layout

Fitting elements into a grid in a responsive way


Consider a <div> element that contains <button> elements:

<div id="box">
    <button class="button">1</button>
    <button class="button">2</button>
    <button class="button">3</button>
    ...
</div>

I want to fit these elements into a grid pattern, so that

  1. buttons are of equal dimensions and have a fixed minimum width,
  2. a maximal amount of buttons is stacked on each row,
  3. button width is adjusted so that each row is filled completely,
  4. and this behavior persists when #box is resized.

Is there a way to do so using native HTML/CSS features (without using JavaScript)? I tried using the new CSS Flexbox layout:

#box {
    display: flex;
    width: 500px;
    height: 500px;
}

.button {
    flex: 1 1 auto;
    min-width: 40px;
    height: 40px;
}

But this doesn't work..

Thanks for your help!


Solution

  • You can use CSS flex for this, as you suspected.

    flex-wrap is what you were missing, as well as using percentages for responsiveness.

    #box {
      display: flex;
      flex-wrap: wrap;
    }
    #box > * {
      flex: 1 0 100px; /* each button should be at least 100px wide */
    }
    <div id='box'>
      <button class='button'>1</button>
      <button class='button'>2</button>
      <button class='button'>3</button>
      <button class='button'>4</button>
      <button class='button'>5</button>
      <button class='button'>6</button>
      <button class='button'>7</button>
      <button class='button'>8</button>
      <button class='button'>9</button>
      <button class='button'>10</button>
      <button class='button'>11</button>
      <button class='button'>12</button>
      <button class='button'>13</button>
      <button class='button'>14</button>
      <button class='button'>15</button>
      <button class='button'>16</button>
    </div>