CSS PREprocessors

Conditionals

by

If/else conditions are incredibly useful when you want a part of your code to depend on something else. This gives maximum flexibility to write the type of logic that meets your needs.

Conditionals inside declarations

Supoort for if statements within a declaration. Less uses a slightly unconventional syntax, but works as expected.

.if-condition {
  foo: bar;
  & when (1 = 1) {
    baz: qux;
  }
}
.if-condition {
  foo: bar;
  @if 1 == 1 {
    baz: qux;
  }
}
.if-condition
  foo: bar
  @if 1 == 1
    baz: qux
.if-condition
  foo: bar
  if 1 == 1
    baz: qux
.if-condition {
  foo: bar;
  @if 1 == 1 {
    baz: qux;
  }
}
.if-condition {
  foo: bar;
  baz: qux;
}

Ternary operators

Ternary operators allow for a single-line if/else test in the format of x > 0 ? true : false.

.if-ternary {
  one-equals-one: if(1 == 1, true, false);
}
.if-ternary
  one-equals-one: if(1 == 1, true, false)
.if-ternary
  one-equals-one: 1 == 1 ? true : false
.if-ternary {
  one-equals-one: true;
}

Interpolate conditionals inside properties

Ability to interpolate if statements inside property names.

.if-within-property {
  #{if(1 == 1, "property", "false")}: bar;
}
.if-within-property
  #{if(1 == 1, "property", "false")}: bar
.if-within-property
  {1 == 1 ? "property" : "false"}: bar
.if-within-property {
  property: bar;
}

Interpolate conditionals inside selectors

Ability to interpolate if statements inside selectors - there probably aren't a lot of use cases for using tests inside a selector but one never knows.

.if-within-selector--#{if(1 == 1, "true", "false")} {
  foo: bar;
}
.if-within-selector--#{if(1 == 1, "true", "false")}
  foo: bar
$if-result = 1 == 1 ? "true" : "false"

.if-within-selector--{$if-result}
  foo: bar
.if-within-selector--true {
  foo: bar;
}

Interactive

Leave a comment below or suggest improvements on GitHub.