Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Viewport units, keeping aspect ratio?

So I've just discovered viewport units, and I really want to use them.

First challenge: My element has a "base size" of 760x670 pixels. I want to use viewport units to scale it up so that either the height is 100vh, or the width is 100vw, whichever is smaller.

Unfortnately, although I can use 100vmin to get the smaller of the two, I can only apply it to the width or the height, not both.

Currently I'm using:

#root {
    width: 760px;
    height: 670px;
    width: 100vw;
    height: calc(670vw/760);
}

This scales the width to fit the screen, resulting in vertical scrolling. This isn't too bad, but I'd prefer it if I could actually have it fit the viewport.

like image 921
Niet the Dark Absol Avatar asked Jan 02 '13 00:01

Niet the Dark Absol


1 Answers

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

like image 139
Šime Vidas Avatar answered Sep 28 '22 06:09

Šime Vidas