[CSS Trick] Create Responsive Layouts without @media Query

edindevto

Ed is Taking Note

Posted on June 10, 2022

[CSS Trick] Create Responsive Layouts without @media Query

We can use auto-fit to create a simple responsive layout of items without writing any @media query code by setting grid columns like:

grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
Enter fullscreen mode Exit fullscreen mode

The above means:
Each grid column has minimum width of 150px, and maximum width of 1 faction unit;
Auto-fit FITS the CURRENTLY AVAILABLE columns into the space by expanding them so that they take up any available space.

Example:

<div class="container">
  <div class="item">ITEM 1</div>
  <div class="item">ITEM 2</div>
  <div class="item">ITEM 3</div>
  <div class="item">ITEM 4</div>
  <div class="item">ITEM 5</div>
  <div class="item">ITEM 6</div>
  <div class="item">ITEM 7</div>
  <div class="item">ITEM 8</div>
</div>
Enter fullscreen mode Exit fullscreen mode
.container {
  background-color: violet;
  padding: 30px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  grid-gap: 15px;
}

.item {
  background-color: lightseagreen;
  padding: 10px;
  height: 300px;
}

Enter fullscreen mode Exit fullscreen mode

Result:

Image description

Image description

Image description

💖 💪 🙅 🚩
edindevto
Ed is Taking Note

Posted on June 10, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related