CSS3: Viewport Units – New Units for Responsive Designs
Developing web designs that adjust to the width or - if needed - the height of a browser window is easy with percentage-based values. You will probably be doing this on a daily basis, optimizing your website for tablets and smartphones. No matter the element, text blocks, images, everything adjusts to the size given.
But using percentage-based values is not always the best way to define sizes in relation to the browser window. Think of font sizes. A font size cannot be defined to react to a changing width of the browser window, at least not percentage-based. CSS3 introduces new units that explicitly address this problem.
Viewport Units for More Flexible Size DefinitionsThe units „
vw“ and „
vh“ define a width/height relative to the window size. We use „
vw“ for „
view width“ and „
vh“ for „
view height“. These so-called viewport units allow us to define sizes in relation to the recent size of the browser window.
Our example element will take up 50% of the window width and 100% of the window height. While percentage-based values always relate to their parent element, viewport units always relate to the window size. It is even possible to define heights in relation to width and vice versa.
Our example defines the height of the element to be 50% of the window width. Scaling down the window width alters the element's height.
Universal Font Size Fits Due to Viewport UnitsIf you want to secure a decent typography, you will want to make sure, that fonts are displayed in acceptable sizes, no matter the device it's being displayed on. Especially large headlines need to be taken care of, to avoid having them look horrible. Use viewport units to define your font in relation to the width of the browser window.
Our example defines the font size to be 10% of the window width. Thanks to „
vw“, the font size, defines for „
h1“ will now always adjust to the browser window.
Define Sizes Depending on The Aspect RatioTo add to the units „
vw“ and „
vh“, we got the units „
vmin“ and „
vmin“ we define a size either in relation to the window height or in relation to the window width, depending on which value is smaller. I s the width smaller than the height, „
vmin“ will relate to the width. You can imagine what „
vmax“ does. Yup, the same, only in relation to the higher value.
In this example our element will receive a width of 20% of the window width while the window width is smaller than the height. Is the height smaller than the width, the element will be defined as being 20% of the window height. It's easy, once you played around with it a bit.
You won't believe it, but viewport units are supported by all major browsers. Even the Internet Explorer is able to properly work with them, from version 10 onwards, at least. Firefox added support from version 19, Chrome from version 20.