I have done a project with a lot of code duplicity, so the problem occurs because I have to write the class in each query. I'm trying to improve performance here. In order to do that, I want to use dynamic values for styling. For example, the way CSS is being used here, but in ten different places using the same animation.
$center : 590px;
.container {
width: $center;
}
@media only screen and (max-width: 1660px){
//here I want to change $center to 490px;
// =================================================
// but the way that I found is to duplicate it
$center: 490px;
.container {
width: $center;
}
/*note : if I don't call the '.container' everytime that I'm changing the $center variable it does not work,
I have some animations that must use the variables .
*/
}
CodePudding user response:
You can make use of @mixin
and @include
to avoid duplication.
@mixin media-container($center) {
@media only screen and (max-width: 1660px) {
.container {
width: $center;
}
}
}
In order to use the @mixin
in any classes you want, you can add the following to the class you want to use this in:
.container-class {
@include media-container(540px);
}
Note that the 540px
above can be replaced with any configuration you want for $center
variable, which would change the width for your container.
Documentation: https://sass-lang.com/documentation/at-rules/mixin
CodePudding user response:
SCSS variables are static (compile time) to do what you want you need to use CSSVariables that are dynamic (run time) - something like this
.container {
width: var(--width, 590px); /* default */
}
@media only screen and (max-width: 1660px){
.container {
--width: 490px;
}
}
If you need to set multiple values - you can use Sass nesting to make it a little easier to type
.container {
width: var(--width, 50px);
@media (min-width: 100px) { --width: 100px; }
@media (min-width: 200px) { --width: 200px; }
@media (min-width: 300px) { --width: 300px; }
...
}
// output
.container {
width: var(--width, 50px);
}
@media (min-width: 100px) {
.container { --width: 100px; }
}
@media (min-width: 200px) {
.container { --width: 200px; }
}
@media (min-width: 300px) {
.container { --width: 300px; }
}