Maintain aspect ratio of a div according to height [duplicate]
Asked Answered
M

1

7

I have to maintain the aspect ratio of a div with respect to the height on window resize.

I can maintain the aspect ratio(x:y) with regard to the width(X%) using padding-bottom; or padding-top;.

So from the analogy, I tried using padding-left;

.wrapper{
   height: Y%,
   position: relative;
}

.wrapper:after{
   padding-left: Y(x/y)%;
   display:block;
}

But the percentage value of padding-left does not give any width to the wrapper.

How can I maintain the aspect ratio of that div according to its height?

Mincemeat answered 21/5, 2014 at 16:38 Comment(2)
Inshort you want a responsive div block keeping an aspect ratio of height and width?Depolarize
yes, but w.r.t to height.Mincemeat
D
2

As % padding/margin are calculated according to the width of the contrainer, you can't use the "padding technique" to maitain aspect ratio according to the height.

For a CSS solution, you will have to use vh units :

vh : 1/100th of the height of the viewport.

Source

For browser support see canIuse


Example for a 1:1 aspect ratio :

DEMO

CSS

div{
    width: 50vh;
    height: 50vh;
}
Dameron answered 21/5, 2014 at 16:45 Comment(1)
Unfortunately, this is relative to the entire window. I hope there's a solution out there relative to the container...Boyish

© 2022 - 2024 — McMap. All rights reserved.