Vertical Media Queries In Use

Note: This article, like most articles about responsive design, is best viewed on a desktop browser. I’m not hating on tablets, mobile phones, or whatever wild doodads you might be using – It’s just that you will be able to test the responsive changes much more easily in a browser that can be scaled manually.

Responsive design has become a huge part of how the web handles different size devices and viewports. Mostly, responsive site only pay attention to the width of the viewport and scale or rearrange content accordingly. Since most sites scroll along the y-axis, the height of the vewport is usually of little consequence. However, when building Code Carpenter I stumbled upon a use for that rarest of css birds: the vertical media query!

If you are viewing this site on a decent-sized desktop browser, you will notice that the “header” area on the left-hand side (which is home to the logo and the main navigation), stays in place as the rest of the content scrolls. Nothing unusual here. I simply adjusted theĀ position property:

.header{ position:fixed; }

Of course, the header doesn’t behave this way on all devices and at all widths. If you make your browser window narrow enough (or view the site on a mobile device), you will notice that the header position becomes relative and it moves to the top of the content. Again, pretty standard.

But what if you are using a viewport that is still wide enough that the header stays on the side, but so short that you can’t see all of the navigation links? This may seem like a pretty rare occurrence, but it is exactly what happens on my Nexus 7 in landscape orientation. And this, my friends, is where vertical media queries come in handy!

Using Chrome Dev Tools, I can see that the header renders at 521 pixels tall in my browser. So, allowing for a little breathing room in case other browsers calculate things a bit differently, I put together a media query that looks like this:

@media screen and (max-height: 550px){
.header{position:absolute}
}

The absolute positioning keeps the header in exactly the same place, but allows it to scroll with the rest of the page. It couldn’t really be much simpler. Go ahead and make your browser a little bit shorter to see it in action.

Have you found any interesting uses for vertical media queries? Let us know in the comments.

One Response to “Vertical Media Queries In Use”

  1. Harshil Shah

    Could you possibly write a post about how one can use media queries to have a navbar aligned vertically for desktop-class devices and horizontally on smaller ones, as with this site? It’s the thing that I haven’t been able to get working correctly on my new Bootstrap project. Thanks!

    Reply

Leave a Reply