Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary condition on class in Sass

Tags:

css

sass

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';
}
like image 504
Baldráni Avatar asked May 18 '17 09:05

Baldráni


People also ask

Can we use conditions in SCSS?

No, We can not use if-else conditions in CSS as CSS doesn't support logics.

How do you write 3 conditions in a ternary operator?

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.

Can we use ternary operator in CSS?

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.

What is ternary operator with example?

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.


1 Answers

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');
  }
}
like image 170
llobet Avatar answered Nov 13 '22 19:11

llobet