htmlcsscss-grid

How to Keep Label and Input Together in Responsive CSS Grid Layout?


I have an HTML structure where labels and inputs are placed inside a div with a grid layout. Here’s my code:

div {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
<div>
  <span>Label 1</span>
  <span><input type="text" placeholder="label 1"></span>
  <span>Label 2</span>
  <span><input type="text" placeholder="label 2"></span>
  <span>Label 3</span>
  <span><input type="text" placeholder="label 3"></span>
</div>

The grid works responsively, but since labels and inputs are separate elements, when the screen size changes, they get misaligned.

On large screens, I want 4 columns (Label + Input stays together). On medium screens, I want 2 columns (Label + Input still together). But on some screen sizes, it automatically creates 3 columns, breaking the label-input pair into different lines. Requirement: I don't want 3 columns because it splits labels from their respective inputs. However, I cannot change the HTML structure (e.g., wrapping label and input inside a ).

Question: How can I ensure that each label stays with its corresponding input without changing the HTML structure? Is there a pure CSS solution to enforce only 4, 2, or 1 columns, preventing 3-column layouts?


Solution

  • When using grid-template-columns you can state multiple column definitions, each having their own width definition, inside the repeat:

    div {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(75px, 1fr) minmax(150px, 1fr));
    }
    <div>
      <span>Label 1</span>
      <span><input type="text" placeholder="label 1"></span>
      <span>Label 2</span>
      <span><input type="text" placeholder="label 2"></span>
      <span>Label 3</span>
      <span><input type="text" placeholder="label 3"></span>
    </div>