Search code examples
csslayoutcss-gridautofill

CSS grid auto-fill with always two columns


I have a grid container that has multiple labels and inputs. Is it possible to configure the grid in a way that it auto-fills the space with always two columns so that the label breaks the line with its corresponding input?

Grid before resize:

Label Input Label Input Label Input

Grid after resize:

Label Input Label Input
Label Input

Solution

  • Simply wrap inputs inside their label:

    .grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      grid-gap:5px;
    }
    
    
    input{
      width:50%;
      float:right;
    }
    <div class="grid">
      <label>label <input type="text"></label>
      <label>label <input type="text"></label>
      <label>label <input type="text"></label>
      <label>label <input type="text"></label>
      <label>label <input type="text"></label>
      <label>label <input type="text"></label>
    </div>