如何保持div包含在视口中,同时保持宽高比 [英] How to keep a div contained within the viewport whilst maintaining aspect ratio

查看:193
本文介绍了如何保持div包含在视口中,同时保持宽高比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

存在一个方形的div,它是一个任意百分比宽度(和相同的高度),需要与窗口缩放。



它必须在边界内的视口(即:不剪切外部)并保持其正方形形状 - 本质上重复了CSS的 background-size:contains; 特征。



我需要支持iOS Safari v3.2,所以我不能使用 vw / vh / vmin / vmax / em>更喜欢仅使用CSS的解决方案。



您可以使用:后设置

在CSS



DEMO http:// jsfiddle。 net / kevinPHPkevin / 5tzk3 / 307 /

  .wrapper:after {
padding-top:100 %; / *设置比率* /
display:block;
content:'';
}

说明:



这是通过插入: c>,然后给div一个填充顶部100%,因此推动div的底部下来工作。如果你把它改成,例如 padding-top:56.25%; 它将给出一个16:9的比率。填充不会干扰div的内容,因为:之后只插入:在此元素内将受到影响。在这种情况下,没有任何元素使用:之后,因为你总是使用一个新的div的效果。



已编辑



DEMO http://jsfiddle.net/kevinPHPkevin/5tzk3/309/



停止扩展超出点设置 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包含在视口中,同时保持宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆