4

I am in the process of developing a new starter theme for myself. Within it, I have a number of breakpoints I wish to use throughout the theme. Rather than manage the breakpoints for every single media query, I wanted to set CSS variables as the breakpoint pixel value and call on the variable inside the media query. Below is an example of how (ideally) this would work

:root {
  --medium: 1024px;
}

p {
  color: black;
}

@media screen and ( min-width: var(--medium) ) {
  p {
    color: red;
  }
}
<p>Text I want to be red in screens larger than 1024px.</p>

This logic sadly does not work in regular CSS/CSS3. Is anyone familiar with a method of creating a single point where I can adjust media query breakpoints for the whole theme without using a preprocessor? Thanks in advance!

JMC_3030
  • 119
  • 2
  • 8
  • 1
    You can't use var() in media query. Ref: https://stackoverflow.com/questions/40722882/css-native-variables-not-working-in-media-queries – rangerz Mar 24 '20 at 07:12

2 Answers2

1

You can accomplish this with matchMedia.

I gave a usage example in this answer.

grandinero
  • 1,155
  • 11
  • 18
0

This is not currently possible as referenced above by @rangerz.

I have taken to just splatting the actual values in the media queries in all of my CSS files marked with a comment:

:root {
    --breakpoint-md-max: 767.98px /*var(--breakpoint-md-max)*/;
    --breakpoint-md-min: 768px /*var(--breakpoint-md-min)*/;
}

@media (min-width: 768px /*var(--breakpoint-md-min)*/ ) {
    #body {
        background: green;
    }
}

This allows me to do a global replacement if I ever need to change this "constant" value.

Plus, one day, when env() is supported, I can remove this unsightly blemish in one shot. :)

Jersey Dude
  • 527
  • 1
  • 5
  • 16