Is there a possibility to use a ternary condition in Sass especially on class object ? Something which would look like :
[class*="fa-caret-"]{
&:left ? 'top: -45' : 'top: 45';
}
No, We can not use if-else conditions in CSS as CSS doesn't support logics.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
The inner set of curly braces is the object of CSS properties and values. If you have multiple properties whose values are determined by the same condition, you could use the ternary operator to return an entire object of properties and values.
It helps to think of the ternary operator as a shorthand way or writing an if-else statement. Here's a simple decision-making example using if and else: int a = 10, b = 20, c; if (a < b) { c = a; } else { c = b; } printf("%d", c); This example takes more than 10 lines, but that isn't necessary.
It depends on what you want to achieve, but here you have an example of a mixin iterating over a list of elements and a ternary operator for changing a value.
$carets: left right;
@each $caret in $carets{
$symbol: if($caret==left,'-','');
.fa-caret-#{$caret}{
top: #{$symbol}45px;
}
}
If you want more elements, or setting properties use a map instead of a list (then, you maybe don't need any ternary operator):
$carets: (
(
'name': left,
'value': -45px
),
(
'name': right,
'value': 45px
)
);
@each $caret in $carets{
.fa-caret-#{map-get($caret, 'name')}{
top: map-get($caret, 'value');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With