How to register styles with media queries?

I’m currently migrating an old legacy theme to Sage. How can I include some css files and specify media expressions for them? Specifically, how do I implement the following registration?

wp_register_style( 'general-desktop', '/css/general/general-desktop', 'not all and (max-width: 990px)' );
wp_register_style( 'general-mobile', '/css/general/general-mobile', '(max-width: 990px)' );

I use Bud.js for building assets. And whole project already migrated to bedrok.

You can use enqueueCss to pass the media:

bundle('name')->enqueueCss('<media here>')

https://github.com/roots/acorn/blob/ef12fafc978ece016e0f6883d0d378bf857592fa/src/Roots/Acorn/Assets/Concerns/Enqueuable.php#L44-L52

…but I wouldn’t serve two separate stylesheets for two different device sizes personally, since that’s a pretty outdated approach at this point. It’s also not recommended to serve multiple bundles on a page.

1 Like

Technically, this is the solution except for an important clarification: even if your entry does not contain any JavaScript, you still have to call the enqueueJs. Otherwise, the styles will not be injected to the page at all in dev mode.

bundle('general-desktop')->enqueueCss('not all and (max-width: 990px)');
bundle('general-mobile')->enqueueCss('(max-width: 990px)');
bundle('general-desktop')->enqueueJs();
bundle('general-mobile')->enqueueJs();

It’s also worth noting that in development mode, styles are injected “as is” and completely ignore the established media rules. Therefore, you additionally have to wrap styles in the middle of each file in media expressions

/* general-desktop.css */
@media not all and (max-width: 990px) {
  /* whole file content */
}
1 Like