CSS

Creating an Aspect Ratio Box with CSS `aspect-ratio`

Maintain a specific width-to-height ratio for any element, like images or video players, using the modern CSS `aspect-ratio` property. Ensures consistent sizing without JavaScript or padding hacks.

.aspect-ratio-box {
  width: 100%; /* Or any specific width */
  aspect-ratio: 16 / 9; /* Sets a 16:9 aspect ratio */
  background-color: lightblue;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.5em;
  color: #333;
  border: 2px solid royalblue;
}

/* Example for a 1:1 square */
.square-box {
  width: 150px;
  aspect-ratio: 1 / 1;
  background-color: lightgreen;
  border: 2px solid darkgreen;
}
How it works: The `aspect-ratio` CSS property is the most straightforward and modern way to define a preferred aspect ratio for an element, which will be used in the calculation of auto sizes and other layout functions. Here, `aspect-ratio: 16 / 9` tells the browser to automatically calculate the height of `.aspect-ratio-box` based on its width, ensuring it always maintains a 16:9 ratio. This is incredibly useful for responsive media containers, replacing older padding-top hacks and providing a native solution.

Need help integrating this into your project?

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

Hire DigitalCodeLabs