CSS

Creating Aspect Ratio Boxes in a CSS Grid

Implement responsive grid items that maintain a consistent aspect ratio, perfect for image galleries, video embeds, or content cards, using modern CSS aspect-ratio.

.aspect-grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
    padding: 20px;
    background-color: #f0f8ff;
}

.aspect-grid__item {
    display: flex; /* To vertically center content */
    justify-content: center;
    align-items: center;
    background-color: #e6f7ff;
    border: 1px solid #a0d9ff;
    color: #333;
    font-weight: bold;
    font-family: sans-serif;
    border-radius: 8px;
    box-sizing: border-box;
    /* Modern approach: Define aspect ratio directly */
    aspect-ratio: 16 / 9; /* Example: 16:9 aspect ratio. Use 1 / 1 for square. */
}

/* For browsers without 'aspect-ratio' support, a common fallback:
.aspect-grid__item-fallback {
    position: relative;
    width: 100%;
    padding-bottom: 56.25%; /* (9 / 16) * 100% for 16:9 aspect ratio */
    height: 0;
    overflow: hidden;
}
.aspect-grid__item-content-fallback {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}*/
How it works: This snippet demonstrates how to create grid items that maintain a specific aspect ratio, crucial for visually consistent galleries, video embeds, or content cards. The modern `aspect-ratio` CSS property is used directly on the grid item, making it simple and efficient. A commented-out fallback shows the traditional `padding-bottom` trick, where a percentage padding (relative to the item's width) ensures the height scales proportionally, useful for older browsers or when more control over inner content positioning is needed. The `grid-template-columns` setup ensures a responsive grid with a fluid number of columns and a minimum item width.

Need help integrating this into your project?

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

Hire DigitalCodeLabs