Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 218
red-devil Avatar asked May 21 '14 16:05

red-devil


People also ask

How do I keep my div aspect ratio?

In the HTML, put the player <iframe> in a <div> container. In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.

How do I make a div stay the same size?

if you set width:500px; and height:300px; (or whatever size you want) the div should stay the same size. Also, you can set overflow:hidden; so that if whatever is in the div goes beyond those bounds, it is not shown, and does not resize the div.

How do you maintain height width ratio of an image?

The Simple Solution Using CSSBy setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.


1 Answers

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;
}
like image 62
web-tiki Avatar answered Sep 19 '22 15:09

web-tiki