问题
There exists a square div that is an arbitrary percent wide (and the same amount high) that needs to scale with the window.
It must stay within the bounds of the viewport (ie: not clipping outside) and maintain its square shape - essentially duplicating the background-size: contain;
feature of CSS.
I need to support iOS Safari v3.2, so I can't use vw/vh/vmin/vmax
and would strongly prefer a CSS-only solution.
回答1:
You can set it using :after
in CSS
DEMO http://jsfiddle.net/kevinPHPkevin/5tzk3/307/
.wrapper:after {
padding-top: 100%; /*Sets ratio*/
display: block;
content: '';
}
Explanation:
This works by inserting no content :after
and then giving the div a padding top of 100%, thus pushing the bottom of the div down. If you change it to, say, padding-top: 56.25%;
it would give a 16:9 ratio. The padding does not interfere with the content of the div as it is inserted :after
and only elements that are associated with :after
within this element would be affected. In this case there are no elements that use :after
as you'd always use a new div for this effect.
Edited
DEMO http://jsfiddle.net/kevinPHPkevin/5tzk3/309/
to stop it expanding beyond a point set a max-width
and max-height
.wrapper {
width: 50%;
display: inline-block;
position: relative;
max-height:350px;
max-width:350px;
}
回答2:
To follow up on Vector's answer in regards to cropping on the bottom:
If you have access to vw/vh you can ensure the bottom never gets cropped by setting the max-width to be 100% of the viewport height, and max-height to be 100% of the viewport-width.
e.g.
max-width: 100vh; max-height: 100vw;
I know the original poster indicated they did not have access to this. Just pointing this out if you find this page like I did and DO have access.
来源:https://stackoverflow.com/questions/18296378/how-to-keep-a-div-contained-within-the-viewport-whilst-maintaining-aspect-ratio