Basically I am attempting to set a CSS value based on whether a value passed into an SCSS mixin is even or odd.
Done some looking around and have found diddly squat. Any mention of odd / even in a search term with CSS/SCSS just results in :nth-child results.
Remainder operator doesn’t work in CSS so that method of determining an odd / even number wont work. I then attempted to go down the route where a number divided by 2 would result in either a number type or integer type depending if it was even or odd, nope.
My only feasible option seems to be
$valType1: "odd";
@if $val1 == 2 {
$valType1: "even";
} @else if $val1 == 4 {
$valType1: "even";
} @else if $val1 == 6 {
$valType1: "even";
} @else if $val1 == 8 {
$valType1: "even";
} @else if $val1 == 10 {
$valType1: "even";
} @else if $val1 == 12 {
$valType1: "even";
} @else if $val1 == 14 {
$valType1: "even";
} @else if $val1 == 16 {
$valType1: "even";
} @else if $val1 == 18 {
$valType1: "even";
} @else if $val1 == 20 {
$valType1: "even";
} @else if $val1 == 22 {
$valType1: "even";
} @else if $val1 == 24 {
$valType1: "even";
} @else if $val1 == 26 {
$valType1: "even";
}
@if $valType1 == "even" {
background-color: red;
}
There’s gotta be something. Any help suggestions? Am I overlooking something painfully obvious?
Thank you!
>Solution :
This is a good use of @function instead of a mixin. And you can use the % modulo operator for this.
Added a @mixin for clarity (and another option).
@function evenOdd( $value) {
$number : blue;
@if ($value % 2 == 0) {
$number : red
}
@return $number;
}
@mixin evenOdd( $value ) {
@if ($value % 2 == 0) {
background-color: red;
} @else {
background-color: blue;
}
}
.selector {
background-color: evenOdd(2);
/* compiles to red */
}
.selector {
background-color: evenOdd(3);
/* compiles to blue */
}
.selector {
background-color: evenOdd(4);
/* compiles to red */
}
/* MIXINS */
.selector {
@include evenOdd(2);
/* compiles to background-color: red */
}
.selector {
@include evenOdd(3);
/* compiles to background-color: blue */
}
You can past this into https://www.sassmeister.com/ – and watch the magic happen.