CSS Grid

CSS 2 minutes read

Create a layout where multiple elements are arranged in a grid-like manner, and each element has a flexible width but a fixed aspect ratio.

To achieve this, you can use CSS Grid. Here’s an example:

<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

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

.item {
  padding-bottom: 100%;
  background-color: #ccc;
}

In the HTML, we have a container element that contains three item elements. In the CSS, we set the container to display as a grid and use the repeat() function to create flexible columns that will automatically adjust based on the available space. We also set the minimum and maximum width of each column to be 200px and 1fr (fractional unit), respectively.

For each item element, we set the padding-bottom to 100% to create a fixed aspect ratio of 1:1 (since the width is flexible, the height will adjust based on the padding-bottom value). We also set a background color to make it visible.

With this setup, the three items will be arranged in a grid, and each item will have a flexible width but a fixed aspect ratio of 1:1. The grid-gap property sets the space between the items. You can adjust the values to suit your needs.

See the Pen CSS Grid by Projects Engine (@projectsengine) on CodePen.

Was this article helpful?

Add comment