Explain Codes LogoExplain Codes Logo

Maintain the Aspect Ratio of a div with CSS

html
responsive-design
css
layout
Alex KataevbyAlex Kataev·Feb 28, 2025
TLDR

The CSS aspect-ratio property is your best friend for maintaining div aspect ratios. Here's the 16:9 ratio:

.ratio-box { aspect-ratio: 16 / 9; }

Attach this class to your div:

<div class="ratio-box"> <!-- Your exciting content --> </div>

To alter the ratio, tweak the aspect-ratio values (4 / 3 for a 4:3 ratio). This method is more practical and intuitive compared to pseudo-elements.

Aspect Ratios: An explanation

Aspect ratio refers to the width-height proportion of a div. Maintaining this ratio is essential for responsive designs, ensuring your content scales properly across devices.

Method 1: Padding-Bottom Magic

The good old padding-bottom technique:

.ratio-container { width: 100%; /* will fit to parent's width */ max-width: 100%; /* no overflowing, please! */ position: relative; /* for absolute kiddos */ padding-bottom: 56.25%; /* 16:9 aspect ratio */ box-sizing: border-box; /* includes padding and border in height */ } .ratio-content { position: absolute; top: 0; left: 0; right: 0; bottom: 0; overflow-y: auto; /* scroll me, if content is too much */ }

Got a different ratio in mind? Play with padding-bottom percentage based on width-to-height ratio desired.

Method 2: Viewport Units for a Responsive Flair

Vw (viewport width) and vh (viewport height) allow our design elements to adapt based on viewport size for a more flexible layout:

.flexible-box { width: 50vw; /* Chew on 50% of the viewport width */ height: 28.125vw; /* 16:9 aspect ratio, chuck it relative to width */ min-width: 320px; /* No shrinking beyond this on narrow viewports! */ }

Grid layout & Aspect Ratios

Striving for a grid layout, and concerned about maintaining square ratios? Keep the same units for both dimensions:

.grid-item { width: 33vw; /* Going a third of viewport width */ height: 33vw; /* Still sticking to square ratio */ }

Overflow Issues? We Got You Covered

To manage content overflow within a fixed aspect ratio container, assign the overflow property to allow scrolling:

.overflow-content { overflow-y: auto; /* The vertical marathon */ overflow-x: hidden; /* Keep the horizontals on the down-low */ }

The Power of Placeholder Images

Using a placeholder image matching your desired aspect ratio can be a great band-aid to keep your layout intact while the real content is getting dolled up backstage.

Welcome Back, Old Browser

Though the aspect-ratio property is handier, don’t forget about elder browsers. The padding-bottom method is still welcomed by our old pal, IE9+.