accessing media queries in javascript

2021-08-15

 | 

~2 min read

 | 

242 words

When we write media queries it’s mostly the case that we just need to reference that within our style sheet. What about those cases where we want to know about the rules so that they can be referenced in our Javascript?

Per MDN, the rules created using @media can be accessed with the CSSMediaRule CSS object model interface.

Example

Interactive CodeSandbox

console.log({ styleSheets: document.styleSheets })
{ styleSheets: [
    CSSStyleSheet {ownerRule: null, cssRules: CSSRuleList, rules: CSSRuleList, type: "text/css", href: null, …},
    CSSStyleSheet {ownerRule: null, cssRules: CSSRuleList, rules: CSSRuleList, type: "text/css", href: null, …},
    CSSStyleSheet {ownerRule: null, cssRules: CSSRuleList, rules: CSSRuleList, type: "text/css", href: null, …}
    ]
}

In this case, the app has three separate stylesheets. So, the first step to using the appropriate stylesheet will be looking at the ownerNode property:

ownerNode: style#/src/layout/TileContainer/TileContainer.module.css:-css

Once you’re able to identify the correct stylesheet, however, then it becomes rather trivial to find the different media queries that are applied:

seeing the different media rules

Unfortunately, the rules are not parsed, so if you want to use them as variables in your Javascript, it appears to require parsing the text.

inspecting specific media rules

I haven’t yet figured out when I would need to do this - in fact, it feels like if I did have to start importing my stylesheets into my Javascript for inspection it’d be a code smell, but it’s nice to know it’s possible!



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!