CSS

Responsive Aspect Ratio Boxes in CSS Grid

Learn to create responsive grid items that maintain a consistent aspect ratio as their size changes, using the modern `aspect-ratio` CSS property.

.aspect-grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 1rem;
  padding: 1rem;
  max-width: 1000px;
  margin: 0 auto;
  background-color: #e0f2f7;
}

.aspect-grid-item {
  aspect-ratio: 16 / 9; /* Maintain 16:9 aspect ratio */
  background-color: #007bff;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.5rem;
  border-radius: 8px;
  overflow: hidden; /* Hide overflowing content if any */
}

.aspect-grid-item-square {
  aspect-ratio: 1 / 1; /* Maintain 1:1 aspect ratio (square) */
  background-color: #28a745;
}

/* Example of content within an aspect-ratio item */
.aspect-grid-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}


<div class="aspect-grid-container">
  <div class="aspect-grid-item">16:9</div>
  <div class="aspect-grid-item aspect-grid-item-square">1:1</div>
  <div class="aspect-grid-item">
    <img src="https://via.placeholder.com/1600x900/007bff/ffffff?text=Image+1" alt="Placeholder 16:9 Image">
  </div>
  <div class="aspect-grid-item">16:9</div>
  <div class="aspect-grid-item aspect-grid-item-square">1:1</div>
</div>
How it works: This snippet showcases the `aspect-ratio` CSS property for creating responsive grid items that maintain their proportions. When applied to a grid item, `aspect-ratio` ensures that the item's height adjusts automatically based on its width (or vice versa) to preserve the specified ratio. This eliminates the need for padding-bottom hacks and works seamlessly with CSS Grid's responsive sizing, making it ideal for images, video placeholders, or card layouts where consistent dimensions are crucial as the grid adapts to different screen sizes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs