CSS
Creating Responsive Aspect Ratio Boxes with CSS Grid
Learn to maintain a perfect aspect ratio for embedded content like videos or images within a grid, ensuring responsiveness and proper scaling.
.aspect-ratio-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
}
.box-wrapper {
position: relative;
width: 100%;
/* Use padding-top to create aspect ratio */
padding-top: 56.25%; /* For 16:9 aspect ratio (9 / 16 * 100%) */
background-color: #f8f8f8;
border: 1px solid #ddd;
}
.box-content {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex; /* Flexbox for centering content inside */
justify-content: center;
align-items: center;
background-color: lightblue;
color: #333;
font-family: sans-serif;
font-size: 1.2em;
}
/* Alternative using newer aspect-ratio property */
.box-wrapper.modern {
aspect-ratio: 16 / 9; /* More direct way to set aspect ratio */
background-color: #f8f8f8;
border: 1px solid #ddd;
display: grid; /* Can contain content directly */
place-items: center; /* Center content easily */
}
How it works: This snippet demonstrates two methods for creating responsive elements that maintain a fixed aspect ratio within a CSS Grid layout. The traditional method uses `padding-top` with `position: relative/absolute` to reserve vertical space proportional to the width. The modern approach utilizes the `aspect-ratio` property, which directly defines the preferred aspect ratio, making it simpler and more semantic. Both ensure that content like videos or images scale correctly while preserving their intended dimensions.