I want to create a responsive div
that can change its width/height as the window's width changes.
Are there any CSS rules that would allow the height to change according to the width, while maintaining its aspect ratio?
I know I can do this via JavaScript, but I would prefer using only CSS.
Best Answer
Just create a wrapper
<div>
with a percentage value forpadding-bottom
, like this:It will result in a
<div>
with height equal to 75% of the width of its container (a 4:3 aspect ratio).This relies on the fact that for padding :
Padding-bottom values for other aspect ratios and 100% width :
Placing content in the div :
In order to keep the aspect ratio of the div and prevent its content from stretching it, you need to add an absolutely positioned child and stretch it to the edges of the wrapper with:
Here's a demo and another more in depth demo