CSS
Aspect Ratio with Flexbox/Grid Items
Ensure consistent dimensions for images, cards, or video players within Flexbox or Grid layouts by utilizing the `aspect-ratio` CSS property for responsive, predictable sizing.
.media-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
padding: 20px;
max-width: 1000px;
margin: 0 auto;
}
.media-card {
background-color: #f5f5f5;
border: 1px solid #ddd;
display: flex; /* Using flexbox inside the card for content */
flex-direction: column;
aspect-ratio: 16 / 9; /* Key: Maintain a 16:9 aspect ratio */
overflow: hidden; /* Hide overflowing content */
}
.media-card img {
width: 100%;
height: 100%;
object-fit: cover; /* Ensures image covers the area without distortion */
display: block;
}
.media-card-content {
padding: 10px;
background-color: #fff;
flex-grow: 1; /* Allows content to take remaining space */
display: flex;
flex-direction: column;
justify-content: space-between;
}
.media-card-title {
font-weight: bold;
margin-bottom: 5px;
}
/* HTML Structure Example:
<div class="media-grid">
<div class="media-card">
<img src="https://via.placeholder.com/400x225/A2D2FF/000000?text=Media+16:9" alt="Placeholder Media 1">
<div class="media-card-content">
<div class="media-card-title">Awesome Video Title</div>
<p>Short description of the content.</p>
</div>
</div>
<div class="media-card">
<img src="https://via.placeholder.com/400x225/FFC7EA/000000?text=Media+16:9" alt="Placeholder Media 2">
<div class="media-card-content">
<div class="media-card-title">Another Great Clip</div>
<p>This is a slightly longer text description for the second card item.</p>
</div>
</div>
</div>
*/
How it works: This snippet uses the `aspect-ratio` CSS property to ensure that elements within a Grid (or Flexbox) container maintain specific dimensions, like a 16:9 video or image frame. Each `.media-card` is given `aspect-ratio: 16 / 9;`, which automatically calculates its height based on its width to preserve the ratio. This is incredibly useful for responsive designs where content needs predictable visual sizing regardless of the viewport width. The internal Flexbox (`display: flex; flex-direction: column;`) helps manage the image and text content efficiently within the fixed aspect ratio container.