Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing variable value based on media query

Tags:

css

sass

I'd like to use the same variable for different media queries. Something like this:

$avatar_size: 200px;

@media (#{$tablet_size}) {
  $avatar_size: 150px;
}
@media (#{$mobile_size}) {
  $avatar_size: 100px;
}

The objective is to be able to use this variable in multiple places, so I can just reference the variable and not have to throw in the media queries every time. Like so:

.font-awesome-icon {
  font-size: $avatar_size;
}
img {
  width: $avatar_size;
  height: $avatar_size;
}
.img-wrapper {
  height: $avatar_size;
}

Any way to do this?

like image 322
Doug Avatar asked Jan 21 '18 21:01

Doug


2 Answers

Try using CSS custom properties instead of SASS variables.

@media (min-width: 300px) {
  :root {
    --width: 250px;
  }
}

@media (min-width: 600px) {
  :root {
    --width: 450px;
  }
}

svg {
  width: var(--width);
}

This will change the width of a svg element dependent on the screen size.

Just experiment with it using this JSFiddle.

Note: If you want to use CSS custom properties with SASS expressions, you have to wrap them in #{}. Read more about CSS custom property support in SASS.

@media (min-width: 300px) {
  :root {
    --width: #{$small-width};
  }
}

@media (min-width: 600px) {
  :root {
    --width: #{$wide-width};
  }
}

svg {
  width: var(--width);
}
like image 84
d-k-bo Avatar answered Sep 27 '22 20:09

d-k-bo


This is impossible, variables are assigned values when the Sass is compiled to CSS.

what you can do is this:

$avatar_size: 200px;
$avatar_tablet: 150px;
$avatar_mobile: 100px;

@media (#{$tablet_size}) {
  img {
    width: $avatar_tablet;
    height: $avatar_tablet;
  }
}

@media (#{$mobile_size}) {
  img {
    width: $avatar_mobile;
    height: $avatar_mobile;
  }
}
like image 44
Nir Ben-Yair Avatar answered Sep 27 '22 19:09

Nir Ben-Yair