This question already has an answer here:
- Maintain the aspect ratio of a div with CSS 21 answers
I have a div that I want to set to 90% of its parent container's width, and I want its height to be set so as to achieve a specific aspect ratio, say 3:1.
.mydiv {
width: 90%
height: 30%(of-width);
}
Is there any way to do this that does not involve JavaScript?
Chiming in long after the answer was posted - you can set an element's aspect ratio with plain CSS, without using any aspect-ratio fanciness. It relies on the fact that padding given as a percentage takes its measurement from the width of the parent element, not the height as you might expect. We can take advantage of this, like so:
So, you set the height to 0, and the top-padding to a percentage, and you get a box with a fixed-aspect ratio. Problem is, you need another little tweak to put stuff inside that box. Change the previous code to something like:
Put a
<div class="liner">
inside your aspect-box, and then place whatever content you want inside that.Set the width and then use Javascript
(Rough syntax!)
Dave
If your container div has a fixed width, then your 90% width div has as well a fixed width. Look which is this width (calculate or use a tool like firebug) and then calculate the 3:1 aspect ratio and apply a height in pixels.
If your container div hasn't a fixed width, then the 90% is as well variable. So the only way you have to manage with dynamic values is to use javascript.
UPDATE
There is a
aspect-ratio
property but it's not a standard one. I haven't tested it, but it should work with webkit browsers. Here it's a link talking about this property:http://www.xanthir.com/blog/b4810
If you really want to do this cross-browser, there are two more options:
You can use the workaround explained in following link. It's not very clean because it uses an image, but its author says it works for Firefox 3.5, Safari 4 and Internet Explorer 7 & 8. The link:
http://lab.veille.jp/aspectratio/
Another ugly for this case option (a lot of code) would be using CSS3 media-queries. You should look which is the width of your div for different windows width, calculate the aspect ratio in each case and apply it to the height. The more media-queries you define, smoother it will be.