Search code examples
tailwind-csspostcss

Can I use Tailwind's media query variants in PostCSS?


Tailwind provides responsive utility variants sm, md, lg, xl and 2xl, and you can define your own as well.

I can use them in class names:

<img class="w-16 md:w-32" src="...">

But can I also use them in PostCSS?

For example, I'm hoping to do something like this (the code doesn't actually work):

img {
  @apply w-16;

  /* I want this section to apply whenever the `md` media query applies. */
  md:& {
    @apply w-32;
  }
}

Solution

  • Yes you can do it with @screen directive or screen() function

    img {
      @apply w-16;
    
      @screen md {
        @apply w-32;
      }
    }
    
    img {
      @apply w-16;
    
      @media screen(md) {
        @apply w-32;
      }
    }
    

    Sometimes Tailwind may yelling about not supported nested syntax (depends on your PostCSS config or Preprocessor like Less) so you may change code a little

    img {
      @apply w-16;
    }
    
    @screen md {
     img {
       @apply w-32;
     }
    }
    

    Finally nothing stops you from using variants within @apply if you wish

    img {
      @apply w-16 md:w-32;
    }