SIZING WITH CSS3'S VW AND VH UNITS(使用CSS3的新单位VW和VH)
原文地址:http://snook.ca/archives/html_and_css/vm-vh-units
翻译:AfarWind
CSS3 introduces a few new units. (Oh wait, I've said that before.) So, you've heard about px, pt, em, and the fancy new rem. Let's look at a couple more: vw and vh.
CSS3引入了一些新的单位。之前你可能听过“px”,“pt”,“em”以及那个很让人惊叹,同样是CSS3的新单位的“rem”。现在让我们一起来看下CSS3中的另一对新单位:“vw”和“vh”。
Often times, there are certain elements within our design that we'd like to ensure can fit into the viewport in their entirety. Normally, we'd have to use JavaScript to do this. Check the size of the viewport and then resize any elements on the page accordingly. If the user resizes the browser then the script runs again to resize the elements on the page.
很多时候,我们想要确保某些元素能够全部自适应窗口。通常我们不得不通过JS来实现。首先是知道浏览器视窗的大小然后是相应的调整所有页面上的元素。如果用户调整浏览器视窗的大小,那么JS需要再执行一次来调整页面上的元素来自适应视窗显示。
With vw/vh, we can size elements to be relative to the size of the viewport. The vw/vh units are interesting in that 1 unit reflects 1/100th the width of the viewport. To make an element the full width of the viewport, for example, you'd set it to
width:100vw.通过vw或vh,我们可以调整元素为视窗的相对尺寸。1vw或vh表示当前视窗的宽度或高度的100分之一。比如为了能让元素满屏显示,你可以设置宽度为100vw。
Putting it to good use(巧妙的利用这个特性)
Lightboxes seem like a great candidate for using vw and vh units, since the lightbox is normally positioned in relation to the viewport. For elements positioned in relation to the viewport, however, I find using fixed positioning with top, bottom, left, and right values to be an easier approach—completely forgoing the need to specify height and width at all.
由于Lightbox通常不是固定定位而是相对与视窗来定位的。因此Lightboxes(译者:Lightbox 图片预览效果:自动根据窗口的大小缩放图片,模式窗口,幻灯片方式播放,内容预加载,渐变等效果。)看起来像是使用vw和vh的最佳对象。对于元素相对于视窗定位,我找到一种比使用CSS中的position:fixed定位方式更简单并且不需要设置固定宽度和高度的方式。
A good use case for these new units would be for content that sits within a normal document flow. For example, scrolling this page, I could include a number of screenshots. For those screenshots, I don't want them to exceed the height of the viewport. In this case, I can set a maximum height on my images.
有个很好的例子来证明这些新单位使用之后元素仍然在文档流中。比如:滚动页面的时候可以包含了一些画面。对于这些画面,我不想让他们超过视窗的高度。在这种情况下,我可以设置图片的最大高度。
img { max-height:95vh; }
In this case, I set the height to 95 to give the element a little bit of breathing room while on the page.
这这种情况下,我设置高度为95vh来让元素在页面中只剩一小块活动空间。
Browser Support(浏览器支持)
With rem, we have support across almost all major browsers including IE9. With vw and vh, however, we still have to wait awhile. Internet Explorer 9 is the only browser out right now that supports these units.
对于rem这个单位绝大多数浏览器都支持,包括IE9。但是对于vw和vh我们仍然需要等待。只有IE9支持它。
(译者:其实移动端方面有些安卓自带的浏览器也是不支持的。)

浙公网安备 33010602011771号