问题描述
存在一个方形的div,它是一个任意百分比宽度(和相同的高度),需要与窗口缩放。
它必须在边界内的视口(即:不剪切外部)并保持其正方形形状 - 本质上重复了CSS的 c>,然后给div一个填充顶部100%,因此推动div的底部下来工作。如果你把它改成,例如 padding-top:56.25%; 它将给出一个16:9的比率。填充不会干扰div的内容,因为:之后只插入:在此元素内将受到影响。在这种情况下,没有任何元素使用:之后,因为你总是使用一个新的div的效果。
已编辑
:DEMO
停止扩展超出点设置 max-width 和 max-height
.wrapper {
width:50%;
display:inline-block;
position:relative;
max-height:350px;
max-width:350px;
}
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.
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; }
这篇关于如何保持div包含在视口中,同时保持宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!