Home > OS >  Grid child elements won't wrap despite using auto-fit/fill and explicit values
Grid child elements won't wrap despite using auto-fit/fill and explicit values

Time:09-30

So I'm trying to create a layout that is not functioning the way I think it should function given the CSS grid parameters. Surely, this is a user error but I'm not sure what I'm missing.

The setup is this:

  1. Display parent element as grid
  2. Add first child with a min value of 24rem
  3. Add second child with a fixed value of 19rem

The goal is:

  • When the viewport shrinks, the second child should wrap below the first child.

Given the explicit values, I'm expecting them to wrap when the viewport shrinks. But no matter what values or combinations I'm trying, wrapping doesn't occur. It feels like wrapping it reserved for elements that repeat with the same values such as:

repeat(auto-fit,(200px,1fr))

Here's the sample code:

.main {
  max-width:1000px; 
  background-color:skyblue; 
  margin-left:auto; 
  margin-right:auto;
}

.parent {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(24rem, 1fr) 19rem);
  padding: 20px;
}

.parent .child:first-child {
  background-color: #eeeeee;
  height: 300px;
}
.parent .child:last-child {
  background-color: #cccccc;
 height: 300px;
}
<div class="main">
<div class="parent">
  <div class="child">first</div>
  <div class="child">second</div>
</div>
</div>

What am I missing??

CodePudding user response:

You will need to reset your column template from 2 (or more with autofill) to a real single one via a mediaquerie.

repeat(auto-fill, minmax(24rem, 1fr) 19rem) sets a minimum of 2 columns , one of them has a fixed size of 19rem. If more contents it would turn into 4 columns , and so on :)

possible example :

.main {
  max-width:1000px; 
  background-color:skyblue; 
  margin-left:auto; 
  margin-right:auto;
}

.parent {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(24rem, 1fr) 19rem);
  padding: 20px;
}

.parent .child:first-child {
  background-color: #eeeeee;
  height: 300px;
}
.parent .child:last-child {
  background-color: #cccccc;
 height: 300px;
}
@media  (max-width : 600px)  {
.parent {
  grid-template-columns: 1fr;
  }
}
<div class="main">
<div class="parent">
  <div class="child">first</div>
  <div class="child">second</div>
</div>
</div>

  • Related