CSS media query height greater than width and vice versa (or how to imitate with JavaScript)

css, javascript

Solution

As stated prior, media queries are the way to go.

More specifically, if you are attempting to detect if the viewport is taller than it is wide (height > width), you might take a look at the aspect ratio documentation.

For example, let's say you wanted to hide or show a different title based on when the viewport is tall or wide. Since a `1/1` aspect ratio is a perfect square, you can use a combination of `min-aspect-ratio` and `max-aspect-ratio` to detect when a change between "tall" and "wide" occurs.

The code might look like this:

@media (max-aspect-ratio: 1/1) {
  body {
    background-color: cornflowerblue;
  }
 
  .wide {
    display: none;
  }
}

@media (min-aspect-ratio: 1/1) {
  body {
    background-color: whitesmoke;
  }
 
  .tall {
    display: none;
  }
}

@media (aspect-ratio: 1/1) {
  .wide {
    display: block;
  }
}
<div class="wrapper">
  <h1 class="tall">I'm taller than I am wide</h1>
  <h1 class="wide">I'm wider than I am tall</h1>
</div>

There is a caveat, though. You might have noticed a third media query that checks if the aspect ratio is a perfect square. Because of how media queries currently work with min and max values, there is a 1px point where some weird stuff can happen, and both are active. Having a query that checks for this perfect square scenario prevents the screen from not displaying either title in the case where it is a perfect square.

Problem

The majority of desktop and laptop screens nowadays have a width greater than the height. The screen is "wide" not "tall." Smart phones have done something rather cool by enabling the orientation of the phone to influence how the content is presented. I'd like to do this with media queries, so that if someone on a mac with a big monitor has their browser window sized so that it's very "tall" (height is greater than width) they would see a header and footer. But if they went fullscreen or "wide" (width is greater than height) they would see a sidebar on the left and maybe also the right. I'm trying to take full advantage of wide screens, and orientations and such. How to do this with media queries or javascript?

Original source