Search code examples
cssnext.jscss-modules

Separate CSS link based on window width in NextJS


Is it possible to make NextJS link stylesheets based on media queries? I'm using css modules. Example:

CSS module file:

@media(max-width: 800px) {
  .myClass{
    /* ...mobile styles */
  }
}
@media(min-width: 800px) {
  .myClass{
    /* ...desktopstyles */
  }
}
.myClass {
  /* all media styles */
}

How NextJS creates the links:

<link rel="stylesheet" href="/_next/static/css/<bundle-number>.css">

Desired behavior:

<link rel="stylesheet" href="/_next/static/css/<bundle-number-desktop>.css" media="(min-width: 800px)">
<link rel="stylesheet" href="/_next/static/css/<bundle-number-mobile>.css" media="(max-width: 800px)">
<link rel="stylesheet" href="/_next/static/css/<bundle-number-all-medias>.css" data-n-p="">

I couldn't find any solution in my researches.


Solution

  • The quick answer is, well yes, but actually no.
    If you want the code splitted automatically and handled by Next.js, I don't think it is possible for now (or maybe unless you tweak the custom server approach).

    But for your workaround, simply just add the CSS file with the good ol' days?
    <link rel="stylesheet" type="text/css" href="style.css" your-property-goes-here>

    I think you can put this through the _document.{tsx|jsx}.
    The drawback for your particular case is, you mentioned that you're using CSS module, correct? I'm afraid that you would've probably should stick back to the classic class/className.