-
Notifications
You must be signed in to change notification settings - Fork 746
Description
In this Discourse thread, jimmyfrasche requests the ability for pages to override the (prefers-*) MQs in script, so they can easily integrate a manual toggle in the page without having to do silly duplication of their styles in both an MQ and a selector.
My initial response was that custom MQs would solve this, but they're actually somewhat non-trivial to do.
The trivial solution of "just make a script-based custom MQ that initially defers to (prefers-color-scheme), and can be overridden to true/false if you manually toggle" means that if script doesn't load, you have an unknown (--dark-mode)
MQ in your page that is just always false, so you apply light-mode styles even if the user normally wants dark mode.
Instead you must double-layer them:
<style>
@custom-media --dark-mode (prefers-color-scheme: dark);
/* use @media (--dark-mode) {...} for stuff */
</style>
<script>
/* Assuming that a JS registration overrides any existing CSS-based ones */
CSS.customMedias.set("--dark-mode", ...);
</script>
And this only works for boolean MQs. If they're multi-state, it's trickier; you have to set up distinct custom MQs for each of the states and override all of them in script.
Would it instead make sense to allow authors to override at least the (prefers-*) queries with CSS.customMedias
, supplying a CSS value that's valid for the MQ in question? That way you could instead write:
<style>
@media (prefers-color-scheme: dark) {...}
/* always works */
</style>
<script>
/* override when manual toggle is engaged */
CSS.customMedias.set("prefers-color-scheme", ...);
</script>
(I don't see a particular reason to limit it to only the (prefers-*) queries, but nor do I see a reason to allow it for things like (width). I mildly lean towards allowing override of anything, just so we don't have to think about which ones are allowed and which aren't and keep that list up to date, but I could easily be convinced otherwise.)
Metadata
Metadata
Assignees
Type
Projects
Status
Status