Variables in Stylus CSS Media Queries

Cory picture Cory · Oct 25, 2012 · Viewed 10.4k times · Source

I've tried everything but I can't get the Stylus CSS preprocessor to use variables in media queries.

For instance this doesn't work:

t = 1000px

@media screen and (max-width: t)
    html
        background blue

Anyone know how to do this?

Answer

mr rogers picture mr rogers · Feb 3, 2013

It looks like stylus supports a little cleaner way to do the same thing as of this pull request.

Here, given a block size, I can make styles that center the container in the page, and set the container size to be 1, 2, or 3 blocks wide based on the browser size. Letting the media query be a variable (instead of sticking variables inside the media query line) makes it a bit cleaner than using the unquote method metioned above.

/* in app.styl */

full_block_width = 300px

three_blocks = "all and (min-width: " + 3*full_block_width + ")"
two_blocks = "all and (min-width: " +  2*full_block_width + ") and (max-width: " + (3*full_block_width - 1) + ")"
one_block = "all and (max-width: " + (2*full_block_width - 1) + ")"

.container 
  margin: auto

@media three_blocks
  .container 
    width: (3*full_block_width)

@media two_blocks
  .container 
    width: (2*full_block_width)

@media one_block
  .container 
    width: full_block_width