Sass @if Statements

The @if statement in Sass controllers whether or not it block gets evaluated, which include emitting any CSS that might be inside. The @if includes an expression, which return true or false. If the expression is true, the block is evaluated.

The @else statement can following an @if statement. The @else block will evaluate if the @if expression is false.

The @else if statement can be used when more than one condition needs to be tested. The @else if block is evaluated only if the preceding @if’s expression returns false and the @else if’s expression returns true.

@mixin breakpoint ($size) {
  @if $size == 'medium' {
    @media screen and (min-width: 640px) {
      @content;
    } 
  } @else if $size == 'large' {
    @media screen and (min-width: 1024px) {
      @content;
    }
  } @else if $size == 'xlarge' {
    @media screen and (min-width: 1200px) {
      @content;
    }
  } @else {
    @error "Unknown size #{$size}."
  }
}

main {
  display: grid;
  grid-gap: 5px;
  grid-template-columns: 1fr;
  
  @include breakpoint('medium') {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
  }
  
  @include breakpoint('large') {
    display: grid;
    grid-template-columns: 200px 1fr 1fr 200px;
  }
  
  @include breakpoint('xlarge') {
    display: grid;
    grid-template-columns: 200px repeat(4, 1fr) 200px;
  }
}