www.hornallanderson.com/blog/q-what-do-wet-hot-american-summer-and-css3-media-queries-have-in-common

Q: What do Wet Hot American Summer and CSS3 media queries have in common?

POSTED BY Jason Porter on Oct 14, 2011

Answer: They are two of my favorite things.

Any web-developer worth his weight in geldings has been asked to make backgrounds that stretch to fill the screen.  While not too difficult, this effect had previously required using either Flash or Javascript.  Can't believe it took me this long to realize - but - you can acheive this effect with simple CSS via media queries.  Media queries are kinda like event listeners for CSS and they have been blowing my mind lately (this site uses lots of them; check the source).  Heres how to set that up.

Media queries are kinda like event listeners for CSS and they have been blowing my mind lately...

Figure out the aspect ratio of the image you're dealing with.  For sake of example, lets say your source image is 1000x600.  The ratio there is 5/3.  Then just set the normal attributes, ie { position:fixed; width:100%; height:auto; }

Setup a media query that listens for when the aspect ratio (width/height) of the users screen goes below the ratio of your image.  In our case, we're want to know if the window ever goes below 5/3, and in that event, I want the image to then be scale to height:100% (instead of width:100%). For example, I used @media screen and (max-aspect-ratio:5/3).

You can find a working example of this on the Lab page and the source is page.hax.css.  Of course you might have a slightly different effect you're trying to achieve, but that's the basic idea; tweak as needed.

WRITTEN BY Jason Porter

Add a comment



Submit
(0)