What is postcss-custom-media?
The postcss-custom-media package allows you to define custom media queries in CSS, which can then be reused throughout your stylesheets. This helps in maintaining a consistent and DRY (Don't Repeat Yourself) approach to media queries.
What are postcss-custom-media's main functionalities?
Define Custom Media Queries
This feature allows you to define custom media queries using the @custom-media rule. In this example, a custom media query named --small-viewport is defined for viewports with a maximum width of 30em.
@custom-media --small-viewport (max-width: 30em);
Use Custom Media Queries
Once a custom media query is defined, it can be used in your CSS just like any other media query. In this example, the custom media query --small-viewport is used to change the text color to red for small viewports.
body { color: black; }
@media (--small-viewport) { body { color: red; } }
Other packages similar to postcss-custom-media
postcss-preset-env
postcss-preset-env allows you to use future CSS features today by converting modern CSS into something most browsers can understand. It includes a variety of plugins, including the ability to use custom media queries. Compared to postcss-custom-media, postcss-preset-env offers a broader range of features but may be overkill if you only need custom media queries.
postcss-media-minmax
postcss-media-minmax lets you write simpler and more concise media queries by using the < and > operators. While it doesn't offer custom media queries, it simplifies the syntax of media queries, making them easier to read and write. It is a good alternative if you are looking for a way to simplify your media queries without defining custom ones.
postcss-custom-media
PostCSS plugin to transform W3C CSS Custom Media Queries syntax to more compatible CSS.
Installation
$ npm install postcss-custom-media
Usage
var postcss = require("postcss")
var customMedia = require("postcss-custom-media")
var css = fs.readFileSync("input.css", "utf8")
var out = postcss()
.use(customMedia())
.process(css)
.css
Using this input.css
:
@custom-media --small-viewport (max-width: 30em);
@media (--small-viewport) {
}
you will get:
@media (max-width: 30em) {
}
Checkout tests for more examples.
Options
extensions
(default: {}
)
Allows you to pass an object to define the <media-query-list>
for each
<extension-name>
. These definitions will override any that exist in the CSS.
preserve
(default: false
)
Allows you to preserve custom media query definitions in output.
appendExtensions
(default: false
)
This option only works if preserve
is truthy.
Allows you to append your extensions at end of your CSS.