1

Is there a way to use calc with vh unit in media query for width?

I'm running following code in Chrome 71 (support of calc in media-queries was added in 66), but see following result: calc with px works (red), vh without calc works (blue), but they together don't (green).

In firefox everything is fine.

http://jsfiddle.net/tmor5yvh/

@media all and (min-width: calc(20px - 17px)) {
  body {
    background: red;
  }
}

@media all and (max-width: 100vh) {
  body {
    background: blue;
  }
}

@media all and (max-width: calc(100vh - 17px)) {
  body {
    background: green;
  }
}

PS: Condition means "width without 17px (for vertical scrollbar) is less then height".

Qwertiy
  • 19,681
  • 15
  • 61
  • 128
  • 3
    This might be of use to you: [Chrome Bug Report: calc in Media Queries evaluates to a fixed value](https://bugs.chromium.org/p/chromium/issues/detail?id=915190). From [this question](https://stackoverflow.com/questions/51522724/calc-with-viewport-units-in-media-query-on-supported-browsers), it seems like there's a bug in Chrome, where `vw` and `vh` height values are translated into fixed values. For example, `calc(100vh - 17px)` is misread by Chrome to be `calc(100px - 17px)`. – Tyler Roper Jan 11 '19 at 18:12
  • 1
    Unfortunately, changing your media query to `calc(500vh - 17px)` proves this. It changes to green when the width becomes `517px`. – Tyler Roper Jan 11 '19 at 18:15
  • @TylerRoper, any workaround? – Qwertiy Jan 11 '19 at 18:31
  • Certainly not one I know off the top of my head unfortunately, I haven't dealt with this issue - just felt it was interesting so I did some digging. I'd suggest digging into the chrome bug I linked and see if any of the comments suggest a workaround. – Tyler Roper Jan 11 '19 at 18:32
  • Use JavaScript. CSS doesn't even know the width of the scrollbar, which may or may not be 17px. – Mr Lister Jan 11 '19 at 19:25
  • Use `em` instead of px and see if that works. something like this `(max-width: calc(100vh - 2.5em) ` – Nisarg Jan 11 '19 at 20:47
  • @Nisarg, doesn't seem working... – Qwertiy Jan 11 '19 at 21:10

0 Answers0