6

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.

Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • I'm testing in Chrome. It seems that `vw` units cannot be used inside `calc`. I tried stuff like `height: -webkit-calc(100vw/3)`. The only other browsers which support both `calc` and viewport units are IE10 and Safari 6, neither of which can be installed on my platform (Windows 7). – Šime Vidas Jan 02 '13 at 01:02
  • 1
    Btw, this should be possible with media queries, as you can branch code based on aspect ratio, e.g. `@media all and (min-aspect-ratio: 760/670) { ... }`. – Šime Vidas Jan 02 '13 at 01:09
  • It's a [WebKit bug](https://bugs.webkit.org/show_bug.cgi?id=94158). So forget about Chrome/Safari. Firefox/Opera don't even implement viewport units. It seems that IE10 is the only browser that understands your code. `:)` – Šime Vidas Jan 02 '13 at 01:34
  • @ŠimeVidas You could make a good answer of those two comments. – Pavlo Jan 19 '13 at 17:37
  • @PavloMykhalov I've made it work in IE10. Answer is below. `:-)` – Šime Vidas Jan 19 '13 at 22:43

1 Answers1

11

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

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385