Sass中@custom-media无法应用对应样式的问题排查
@custom-media Isn't Working in Chrome 64 & How to Fix It Let's break down exactly what's going wrong with your blue background and get that responsive layout working as intended.
The Core Issue
Chrome 64 (released in 2018) doesn’t natively support CSS Level 4’s @custom-media syntax. To make matters worse, Sass doesn’t transpile this feature—it just passes the @custom-media rules directly into your compiled CSS, which the browser ignores entirely. That’s why your .presentation element never gets the blue background in the 1025px–1280px range.
Fixes to Try
1. Add PostCSS with postcss-custom-media to Your Workflow
Since Sass won’t handle custom media queries, you need PostCSS to convert the Level 4 syntax into standard media queries that older browsers can understand.
- First, install the required packages:
npm install postcss postcss-custom-media --save-dev - Create a
postcss.config.jsfile to configure the plugin:module.exports = { plugins: [ require('postcss-custom-media')({ importFrom: './custom-media.scss' // Point to your custom media definitions }) ] }; - Update your build script to run PostCSS after Sass compilation. For example, in your
package.json:"scripts": { "build:css": "sass app.scss temp.css && postcss temp.css -o app.css" }
2. Double-Check Your Custom Media Syntax
Your current definitions have a minor syntax inconsistency. Stick to valid CSS Level 4 range syntax to avoid confusion:
@custom-media --desktop (1025px <= width <= 1280px);
Or use the expanded form (better for broader compatibility):
@custom-media --desktop (width >= 1025px) and (width <= 1280px);
3. Alternative: Use Sass Variables (No PostCSS Needed)
If you don’t want to add another tool to your stack, switch to Sass variables for media queries. This works because Sass will compile the variables into standard CSS directly.
In custom-media.scss:
$phone: "(320px < width < 480px)"; $tablets: "(481px < width < 767px)"; $desktop: "(1025px < width < 1280px)";
In app.scss:
@import 'custom-media'; .container{ width: 100vw; height: 100vh; display: grid; grid-template-columns: 60% 1fr; .presentation{ background:#CB3BBF; } @media #{$desktop} { grid-template-columns: 1fr; .presentation{ background:blue; } } }
4. Verify the Compiled CSS
After implementing either fix, check your final app.css file. You should see the media query expanded to standard syntax like this:
@media (1025px < width < 1280px) { .container { grid-template-columns: 1fr; } .container .presentation { background: blue; } }
If you see this, Chrome 64 will apply the styles correctly when the viewport falls in your target range.
内容的提问来源于stack exchange,提问作者DarkFenix

