-2

I want to create a grid in CSS that will have 2 columns by default, but if there's not enough width, merge all elements into 1 column. How can I achieve that?

Currently the width of my 2 columns are defined as 1fr 1fr and the whole container just takes as much horizontal space as it's children need, or as much as is available in the parent.

Max Yankov
  • 12,551
  • 12
  • 67
  • 135
  • Probably the answer here is going to depend on how you are defining "not enough width". Do you have a specific screen width where you want to break from 2 columns to 1? Or is it based on the width of the children? Are the children dynamically sized, or are they all the same constant width? Do any of the answers in [this post](https://stackoverflow.com/questions/43115822/can-i-make-a-css-grid-with-dynamic-number-of-rows-or-columns) help you at all? – Jake Mar 31 '23 at 19:51

1 Answers1

1

This can be achieved with the help of auto-fit and minmax().
In the example below, the columns move to the next row when the width of the container is less than 400px + grid-gap:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-gap: 10px;
}

.grid-cell {
  border: solid 1px;
}
<div class="grid">
    <div class="grid-cell">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dignissimos, sed, sunt consectetur reiciendis vitae illo id expedita provident dolore tenetur eos dolor cupiditate perspiciatis hic necessitatibus rem vel molestiae laboriosam nulla alias eum sapiente eaque quas asperiores ratione architecto corporis.</div>
    <div class="grid-cell">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas, autem!</div>
</div>
imhvost
  • 4,750
  • 2
  • 8
  • 10