24sharon
24sharon

Reputation: 1975

Get screen proportion by dividing width by height in CSS

I try to get the proportion of the screen

This is my CSS that I try, But it does not work

height: calc(50vw - calc(1vw / 1vh)*3);

How can I get the screen width divide by screen height?

Thanks

Upvotes: 2

Views: 1738

Answers (1)

tao
tao

Reputation: 90312

First of all, calc() is not nestable 1. But for what you need, you shouldn't need to nest it. You can use parentheses to set the order of operations (as long as they are legal):

height: calc(50vw - (1vw / 1vh) * 3); /* ❌ - ILLEGAL SYNTAX! */

But that's not legal, for the following reasons:

  • division by concrete units (rem, px, pt) 2 is not possible in calc(). Not even if you do 1px / 1px. The browser won't equate that to 1.
  • even if the division by units was possible and the browser was smart enough to come up with the screen ratio from 1vw/1vh, the second part of your subtraction would result in a numeric value (if, for example, the screen was square, the value would be 3, so your calc would result in calc(50vw - 3)). Which, again, is not legal: 3... what? px, vw, rem?

For details, here's the documentation on calc().


To conclude: as far as I know, there's no way of getting the screen ratio using CSS. But it's fairly simple using JavaScript:

const setRatio = () => {
  document.body.style.setProperty('--vw', self.innerWidth / 100);
  document.body.style.setProperty('--vh', self.innerHeight / 100);
}

setRatio();
window.addEventListener('resize', setRatio)
.box {
  height: calc(50vw - var(--vw) / var(--vh) * 3px);
  border: 1px solid red;
}
<div class="box"></div>


1 - According to this answer, calc() should be nestable. For a period of time, due to an oversight in its grammar, nesting was not possible. Today it's possible, in both theory and practice.
But we still can't add numeric values with unit values, just as we can't divide by unit values.

2 - for the purpose of this answer, percentage % is also considered a concrete layout unit. That's because when used in directional properties (height, max-width, etc) it's calculated as percentage of the relevant dimension of the reference ancestor, on that direction. In other words, it's not a division by 100.

Upvotes: 4

Related Questions