/ Polymer

Using iron-media-query to make responsive layouts in Polymer Apps

Sometimes using flex boxes through the iron-flex-layout isn't enough.

The iron-media-query[1] combined with the dom-if allows you to selective add elements based on the width of the screen.

You should think of iron-media-query like an if, where the condition of the if is based on media queries. You can find a whole bunch of example of media queries at the bottom of app/styles/app-theme.html.

You can ask questions about the displayed port. This is important to know that this is different from the screen size.The display port can be thought of as a window running inside your device. The screen is fixed size but the window can change (e.g. be maximized, shrunk to half, changed orientation).

Here are the types of queries/questions you can ask:

min-width: size
max-width: size
orientation: landscape or portrait

It's important to know that you can do simple conditions or compounded conditions.

Here's an iron-media-query setup do a simple condition

<iron-media-query query="(min-width: 700px)" query-matches="{{isAtLeast700px}}"></iron-media-query>

This means that the variable isAtLeast700px will be set to true if the display port is larger than 700 pixels otherwise isAtLeast700px will be set false.

<iron-media-query query="(max-width: 400px)" query-matches="{{isAtMost400px}}"></iron-media-query>

This means that the variable isAtMost400px will be set to true if the display port is smaller than 400 pixels otherwise isAtMost400px will be set false.

<iron-media-query query="(min-width:500px) and (max-width: 700px)" query-matches="{{isBetween500_700px}}"></iron-media-query>

This means that the variable isBetween500_700px will be set to true if the display port is between than 500 and 700 pixels otherwise isBetween500_700px will be set false.

Now if you combine an iron-media-query with a dom-if now you can selectively display elements.

<iron-media-query query="(min-width:500px) and (max-width: 700px)" query-matches="{{isBetween500_700px}}"></iron-media-query>
<template is="dom-if" if="{{isBetween500_700px}}">
  <!-- anything in here is displayed only when the display port is between 500 and 700 pixels-->
</template>

  1. https://elements.polymer-project.org/elements/iron-media-query ↩︎