Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I just wish CSS offered a simple way to fix the aspect ratio of an arbitrary element.


I have used a hack for this for years. And it seems to be very unknown.

If you want an element to have the aspect ratio 16:9 give it a parent div with width: 100%; height: 0; padding-bottom: 56.25%; position: relative;

then just absolutely position the child element with width 100%; height:100%;

This works everywhere, even in IE8. I am happy I will not have to resort to this anymore in the future, but it will do for now.


It’s pretty common. For example, Bulma.io framework uses it for the .image.is16-9 etc tags.


Ah good to know. I don't use CSS frameworks (except Tailwind recently), but that sounds handy.


That's coming! It's not implemented in any browsers yet, but it should be soon. It was introduced in "CSS Intrinsic & Extrinsic Sizing Module Level 4".

It will use the property "aspect-ratio" with values like "16/9" or "1/1".

MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-rati...

Article about it by Rachel Andrew in Smashing Magazine: https://www.smashingmagazine.com/2019/03/aspect-ratio-unit-c...


You can set the width and height attribute (HTML attribute, not CSS property) today.

Recent Chrome and Firefox use that to determine aspect ratio for jank-free loading.


For images and iframes, but I don't think that works for any element. In any case, hardcoding that kind of information in the HTML is not ideal.


That’s Grrrreat!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: