Search code examples
csslayout

How to make a CSS grid that wraps when the container is too small?


I have a dynamic layout that will either have one or two items in it. I want each item take up half the width even when there is only a single item.

large screen diagram

When there is not enough room for half the width to be greater than a min width (11rem), I want the items to take up the full width and wrap to the next line.

small screen diagram

Ideally this can be done without media queries, so that the layout is dependent entirely on its own size rather than the full viewport size. I'm not sure whether this is a grid layout or a flexbox. I have not been able to get it working with either.

.container {
  display: grid;
  grid-template-columns: repeat(2, minmax(11rem, 1fr));
  gap: 0.5rem;
}
<div class="container">
  <input>
  <input>
</div>

How do I make a layout where each item takes up half the width in a large container and the full width in a small container?


Solution

  • From my article: https://css-tricks.com/responsive-layouts-fewer-media-queries/

    .container {
      --w: 400px; /* control when the items will wrap */
      
      display:grid;
      grid-template-columns: 
        repeat(auto-fill, 
         minmax(clamp(100%/3 + 0.1%,(var(--w) - 100%)*1000,100%/2 + 0.1%),1fr));
      gap: 10px;
      margin: 10px;
    }
    <div class="container">
      <input>
      <input>
    </div>
    <hr>
    <div class="container">
      <input>
    </div>