Resize Div based on height but keep aspect ratio (almost worked out) Strange Reload Error

There are many solutions to maintain the aspect ratio when you change the video size based on the width of the parent div. Most of them depend on the fact that padding-top and padding-bottom are calculated based on width, not height.

I am trying to do something like this, but I want to resize my video depending on the height of the parent div.

To do this, I need to create a div that maintains aspect ratio regardless of height. This can be a kind of a lame way to do it, but I decided to use the image to make it, because I can set the height of the image with the corresponding aspect ratio of 100% and allow to sort height.

I am very close to this work. At the moment, I was able to make the inner div the way I want it to do, except that it will not redraw when the window is resized. However, if I resize the window, then reload it, it works. Any ideas?

Here's a demo (this is not a code issue, I did it locally too)

+7
css height aspect-ratio
source share
1 answer

Good idea using image and height: 100% . This will definitely get a box with the same aspect ratio as the image, but does not overpay the window when the window is resized for any reason.

Here is a demo with a little cleaner CSS and Javascript hacking to fix the rescheduling when the window is resized.

In the demo, I use a 16-pixel by 9-pixel uri image to set the aspect ratio, preventing unnecessary HTTP request. If you need an image with a different ratio, use this site to convert your image into a data uris: http://dataurl.net/#dataurlmaker

I was able to solve the reflowing problem with a very simple jQuery. On the $(window).resize() , I switch on the body of the class, which makes the image of the relationship text-align: left to the text-align: justify , that forces the browser to a refiner field.


browser Support

Works in Chrome, Safari, Mobile Safari, Firefox, and IE9 +. Resizing is pretty smooth, but Safari stutters a little.

IE6 / 7 does not support display: inline-block , so the field has a width of 100% and the correct height. (not a bad supply!)

IE8 correctly determines the height of the window, but the width is only the same as the original image (16 pixels). The only way I found it - to use conditional tags to IE5 HTML5Boilerplate, just to set the parent item to embed display: block , in this demo


CSS only

If you only need a CSS solution, set up an image relationship animation to switch a small number of add-ons in Chrome, Safari and Firefox. However, this constantly causes the browser to re-render the page layout, which is extremely inefficient compared to displaying the page layout when the window is resized.

 .Ratio { animation: myfirst 1s infinite; } @keyframes myfirst { from { padding-top: 1px; } to { padding-bottom: 1px; } } 

Hope this helps!

+4
source share

All Articles