CSS Calc Viewport Units Workaround

CSS Calc Viewport Units Workaround?

Before I answer this, I'd like to point out that Chrome and IE 10+ actually supports calc with viewport units.

FIDDLE (In IE10+)

Solution (for other browsers): box-sizing

1) Start of by setting your height as 100vh.

2) With box-sizing set to border-box - add a padding-top of 75vw. This means that the padding will be part f the inner height.

3) Just offset the extra padding-top with a negative margin-top

FIDDLE

div
{
/*height: calc(100vh - 75vw);*/
height: 100vh;
margin-top: -75vw;
padding-top: 75vw;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: pink;
}

Viewport units, keeping aspect ratio?

I've made it work in IE10:

#elem {
width: 100vw;
height: calc((9/16)*100vw);
}

@media (min-aspect-ratio:16/9) {
#elem {
height: 100vh;
width: calc((16/9)*100vh);
}
}

Live demo: http://jsfiddle.net/C2ZGR/show/ (open in IE10 (preview version available for Windows 7); then re-size window, so that either the width, or height is very small)

I've used an element with the aspect ratio of 16:9, but the code can work for any aspect-ratio - just replace 16/9, and 9/16 with your desired aspect ratio.

Btw, IE10 is the only browser in which this demo will work. Firefox/Opera don't implement viewport units yet, and the WebKit browsers currently have a bug where viewport units cannot be used inside calc().

Safari + CSS: using calc with vh does not work

Safari seems to be kind of buggy with viewport units in general, especially if you go back a version or two. The last time I tried to use vh/vw, I ran into similar issues and ended up making use of the v-unit javascript micro-lib, and it worked out very well.

CSS is rapidly catching up to javascript for things like layout calculations, but when it gets complex, supplementing your css with some light scripting often works better than CSS alone.



Related Topics



Leave a reply



Submit