Animated Media Queries

Avatar of Chris Coyier
Chris Coyier on (Updated on )

UGURUS offers elite coaching and mentorship for agency owners looking to grow. Start with the free Agency Accelerator today.

If you apply a transition on an element for a particular supported property, and that property ever changes, it will use that transition. If a class name on that element changes and the new class changes that property, it will transition (assuming what that class does isn’t remove the transition). If JavaScript literally changes the that style property, it will transition.

Likewise, if a new media query takes affect, and that media query has something in it that changes that property on that element, it will transition. As such, there really isn’t a such thing as an “animated media query” so much as elements that just transition as expected when a new media query starts affecting the page.

Simple Example

.thing-that-moves {
  position: absolute;
  width: 100px;
  height: 100px;
  background: red;
  top: 0;
  left: 0;
  transition: left 0.5s; /* BYO prefixes */
}
@media (min-width: 400px) {
  left: 50px;
}
@media (min-width: 600px) {
  left: 100px;
}

If you were to resize your browser window across those breakpoints, you’d see a red square moving around in response.

Slightly More Complex Layout Example

A few versions ago on CSS-Tricks, I had a search form that would slowly float into position using this exact technique. I’ve recreated that here in a somewhat simple layout, in which a few other things transition as well:

See the Pen Animated Media Queries by Chris Coyier (@chriscoyier) on CodePen

You might have the best luck checking it out in Full Page View.

Animated GIF of it working:

p.s. LICEcap is very useful for creating GIF’s like that.

What else can I do?

They sky is the limit here. It’s just CSS. Change and transition whatever you want. In another version of CSS-Tricks, I drew Mike the Frog from Treehouse out of simple CSS shapes. When different media queries hit, Mike would change shape, color, expression, and position – slowly morphing into the next state through transitions. It was well liked!

What is the browser support?

IE 9+ on the media queries. IE 10+ on the transitions. I wouldn’t sweat the transitions as they are strictly funcandy only (if they don’t transition, it doesn’t matter, they still move). If you need deeper media query support, there is always Respond.js.

Is there any actual reason to do this?

Poops and giggles, yo. This is purely for fun. It can be a little touch just to give your site some spirit. It would be hard to make a business case, but if your performance budget doesn’t have a few bytes for funzies, I feel bad for you son.

Anything to watch out for?

If the stylesheet is parsed fast enough and the transitions get applied to an element while the page is still being laid out, those transitions might be kinda obnoxious. You might want to apply them only after the page is loaded.