Tuesday 26 January 2016

CSS3: Using vw and vh units

VW simply means viewport width while VH is viewport height.

So, you've heard about px, pt, em, and the fancy new rem. Let's look at a couple more: vw and 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.

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.

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.
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.

Browser Support

This feature is supported by all major browsers including internet explorer 9.


Follow me on twitter: http://www.twitter.com/_josiah_king Join me on Google+: https://www.plus.google.com/u/0/113541005774136102412/posts/p/pub?cfem=1

No comments:

Post a Comment