corvid
corvid

Reputation: 11177

Compose a specialized transform with variables in SASS

I have a use case where I must define a transform on an element based on two variables: $horizontal and $vertical.

However, I will ultimately use these in a transform, meaning that I cannot define each variable manually.

In pseudocode, it would look as follows:

@mixin pivotTranslate($horizontal, $vertical) {
  @if $horizontal = 'left'
    transform: translateX(-100%);
  @else if $horizontal = 'right':
    transform: translateX(100%);

  @if $vertical = 'top':
    transform: translateY(100%);
  @else if $vertical = 'bottom':
    transform: translateY(-100%);
}

However, this does not seem to work because transform will be "overriden". What I really want to do is use a mixin with ifs to compose a specialized transform then spool it all together at the end.

How would this be done in sass?

Upvotes: 0

Views: 570

Answers (1)

Daisi
Daisi

Reputation: 2418

@mixin pivotTranslate($horizontal, $vertical) {
  $left-side: '';
  $right-side: '';

  @if $horizontal == 'left' {
    $left_side: translateX(-100%);
  }
  @else if $horizontal == 'right' {
    $left_side: translateX(100%);
  }

  @if $vertical == 'top' {
    $right-side: translateY(100%);
  }
  @else if $vertical == 'bottom' {
    $right-side: translateY(-100%);
  }

  transform: $left-side $right-side;
}

div {
  @include pivotTranslate('left', 'top');
}

/* CSS output generated */
div {
  transform: translateX(-100%) translateY(100%); }

Initialize local variables $left-side and $right-side which can be passed as values to transform

I simplified the mixin using this code. It has the same behaviour the only difference is that I used translate versions as a default value instead of empty strings

@mixin pivotTranslate($horizontal, $vertical) {
  $left-side: translateX(-100%);
  $right-side: translateY(100%);
  @if $horizontal == 'right' {
    $left_side: translateX(100%);
  }
  @if $vertical == 'bottom' {
    $right-side: translateY(-100%);
  }
  transform: $left-side $right-side;
}

Upvotes: 1

Related Questions