CSS

Maintain Aspect Ratio for Responsive Grid/Flex Items

Learn to effortlessly preserve a consistent aspect ratio for elements like images or videos within a responsive CSS Grid or Flexbox layout using the `aspect-ratio` property or the padding-bottom hack.

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

.aspect-ratio-item {
  /* Modern approach: Use aspect-ratio property */
  aspect-ratio: 16 / 9; /* For a 16:9 aspect ratio */
  background-color: lightblue;
  display: flex; /* Optional: for centering content inside */
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;

  /* Fallback/alternative for older browsers (padding-bottom hack) */
  /* If using padding-bottom hack, parent needs position: relative; and child position: absolute; top/left/width/height 0; */
  /*
  position: relative;
  width: 100%;
  padding-bottom: 56.25%; // For 16:9 (9/16 * 100%)
  overflow: hidden;
  */
}

/* If using padding-bottom hack, child content needs to be positioned */
/*
.aspect-ratio-item > * {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
*/
How it works: This snippet shows how to create boxes within a Flexbox or Grid layout that maintain a specific aspect ratio, crucial for responsive images, videos, or card designs. The modern approach uses the `aspect-ratio` property (e.g., `aspect-ratio: 16 / 9;`). For broader browser compatibility, an alternative "padding-bottom hack" can be used, where `padding-bottom` is set as a percentage of the width (e.g., 56.25% for 16:9). This ensures the height scales proportionally with the width.

Need help integrating this into your project?

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

Hire DigitalCodeLabs