0

I use $section-padding: 32px; to set paddings on multiple elements such as

body {
    padding: $section-padding;
}

.section-title {
    width: calc(100% - #{$section-padding *2});
}

.site-footer {
    padding: 60px 0 $section-padding;
}

Now I need to adjust that value when using media queries so instead of updating all of the styles, I would just like to adjust the value of $section-padding for example

@media only screen and (max-width : 1200px) {
    $section-padding: 16px;
}

I've added to my sass

$section-padding: 32px;
$section-padding-lg: 16px;
$section-padding-md: 8px;
$section-padding-md: 4px;

But then I'll still have to update all of the styles everywhere it's used.

Junky
  • 958
  • 7
  • 17
  • 1
    Does a native CSS variable suit your needs? – InSync Mar 21 '23 at 15:08
  • Yes, I considered that and I might have to go that route but I'm trying to avoid having to update all my code. – Junky Mar 21 '23 at 15:09
  • 1
    Add a `--section-padding: 32px;` to `:root`, mirror it using a `$section-padding`, then modify it in the media query. How does that sound? If it works for you I'll post it as an answer. – InSync Mar 21 '23 at 15:13
  • @InSync you should post that as an answer, since it's a great solution and then I won't post the same answer. :) – disinfor Mar 21 '23 at 15:15
  • Does this answer your question? [CSS native variables not working in media queries](https://stackoverflow.com/questions/40722882/css-native-variables-not-working-in-media-queries) Specifically: https://stackoverflow.com/a/40723076/1172189 – disinfor Mar 21 '23 at 15:20
  • 1
    @disinfor Oh well, too bad :P – InSync Mar 21 '23 at 15:21

1 Answers1

0

This is not possible to achieve only with SASS variables because @media rule is read by the browser and SASS code is generated before serving it to the browser.

You can compare SASS variables with CSS variables to achieve this:

:root {
  --section-padding: 32px;
}

@media only screen and (max-width : 1200px) {
    :root {
      --section-padding: 16px;
    }
}

$section-padding: var(--section-padding);

body {
    padding: $section-padding;
}

.section-title {
    width: calc(100% - ($section-padding * 2));
}

.site-footer {
    padding: 60px 0 $section-padding;
}
qiqqq
  • 631
  • 5
  • 10
  • As @InSync suggested I'll give this a go. – Junky Mar 21 '23 at 15:37
  • This is giving me an error when using such as ```padding: ($section-padding * 2);``` Undefined operation: "var(--section-padding) times 2". – Junky Mar 21 '23 at 16:07
  • @Junky I updated my answer, I changed this SASS calculation to standard CSS `calc` only – qiqqq Mar 21 '23 at 17:05