Search code examples
csscss-grid

CSS Grid Columns not Wrapping


I have a particular arrangement of HTML elements, that I'm successfully positioning with the use of CSS Grid to look as follows:

enter image description here

The top of the Form Input here is in line with the bottom of Heading One

The problem is that when the screen is resized, I expected the right hand column to wrap under the first column - as the left and right columns have a min and max width of 300px - but it doesn't. The 2nd column just shrinks in width...

I don't have much control over the HTML layout here, so was looking to solve via grid layout

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 300px));
  column-gap: 96px;
}

.title {
  grid-row-start: 1;
  grid-row-end: 1;
}

.details {
  grid-row-start: 2;
  grid-row-end: span 3;
}

.form {
  grid-row-start: 2;
  grid-row-end: 2;
}

.message {
  grid-row-start: 3;
  grid-row-end: 4;
}

div {
   border: 1px solid black;
}
<div class="container">
    <div class="title">
        Heading One
    </div>
    <div class="details">
        This can contain a lot of text potentially. This can contain a lot of text potentially. This can contain a lot of text potentially
   </div>
   <div class="form">
       Form Input
   </div>
   <div class="message">
       All is good
   </div>
</div>


Solution

  • You should not define the position to have wrapping. Do it like below:

    .container {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 35%)); /* use bigger than 33% to have max 2 columns */
      column-gap: 96px;
    }
    .details,.title {
      grid-column: 1; /* put title and details on first column */
    }
    .details {
      grid-row: span 3;
    }
    
    
    div {
       border: 1px solid black;
    }
    <div class="container">
        <div class="title">
            Heading One
        </div>
        <div class="details">
            This can contain a lot of text potentially. This can contain a lot of text potentially. This can contain a lot of text potentially
       </div>
       <div class="form">
           Form Input
       </div>
       <div class="message">
           All is good
       </div>
    </div>