简体   繁体   中英

CSS Maintain Aspect Ratio not working

This is the strangest thing, I have used this method many times before but it seems to be breaking for me now.

Here is a duplicate question that provides this method as an answer:

Maintain the aspect ratio of a div with CSS

But for some unknown reason it's breaking for me in Firefox and Chrome. From what I can gather it's calculating the padding according to the parent of the element I'm applying the style to...

In this case it's not looking at .test but instead is looking at .parent to calculate the padding:

 .parent { width: 200px; } .test { width: 50px; background: red; padding-top: 100%; }
 <div class='parent'> <div class='test'></div> </div>

That is actually the correct behaviour. You are meant to make the child 100% width and control the sizing with the parent.

Example:

 .parent { width: 200px; } .child { width: 100%; background: red; padding-top: 100%; }
 <div class="parent"> <div class="child"></div> </div>

Here is a nice method proposed on CSS-Tricks that helps you get the correct padding you need for the desired ratio:

Aspect Ratio - 2:1

 .parent { width: 200px; } .child { width: 100%; background: red; padding-top: calc(1 / 2 * 100%); // will give you an aspect ratio of 2:1 }
 <div class="parent"> <div class="child"></div> </div>

Aspect Ratio - 3:1

 .parent { width: 200px; } .child { width: 100%; background: red; padding-top: calc(1 / 3 * 100%); // will give you an aspect ratio of 3:1 }
 <div class="parent"> <div class="child"></div> </div>

Aspect Ratio - 16:9

 .parent { width: 200px; } .child { width: 100%; background: red; padding-top: calc(9 / 16 * 100%); // will give you an aspect ratio of 16:9 }
 <div class="parent"> <div class="child"></div> </div>

You can find the full article here: https://css-tricks.com/aspect-ratio-boxes/

CSS has a property for this

 .square { aspect-ratio: 1 / 1; width: 100px; background: grey; padding: 10px; color: white; }
 <div class="square">a sqaure</div>

update:
there is another way if your support is absolutely crucial and you cant live with firefox being unsupported then here you go. But its a bit janky.

 div { width: 5em; height: 5em; font-size: 3vw; background: grey; padding: 0.5em;} /*em is relative to font-size so you could use that and vw is veiwport width where 100 is all of the veiwport. the size of the shape is now 5 * 3vh*/
 <div>hello</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM