Coop Coop - 4 months ago 22
Sass (Sass) Question

SASS - reference parent of parent

I'm trying to keep my code as DRY as possible. Consider this example:

#parent {
position: relative;

#child {
position: absolute;
top: 0;
left: 0;
}
}


Now I want to add a hover effect on the
#parent
that will alter the
#child
. I know I can do it like this:

#parent {
position: relative;

#child {
position: absolute;
top: 0;
left: 0;
}

&:hover #child {
transform: scale(1.2, 1.2);
}
}


But I'm not happy with this solution. It isn't completely DRY because
#child
is declared twice. Another way to do it is like this:

#parent {
position: relative;
}

#child {
position: absolute;
top: 0;
left: 0;

#parent:hover & {
transform: scale(1.2, 1.2);
}
}


This is arguably more semantic, but no more DRY because
#parent
is declared twice.

Is there a truly DRY way to do this with SASS?

Answer

I have minimum of 5 beautiful ways to do it. i will share 1, if you want more i can share more as well.

Using Functions

@mixin onParentHover() {
  $rootString: #{&};
  $parentIndex: str-index($rootString, " ");
  $parent: str_slice($rootString, 0, $parentIndex - 1);
  $children: str_slice($rootString, $parentIndex);

  @at-root #{$parent}:hover #{$children} {
    @content;
  }
}

Usage

#parent {
  position: relative;
  width: 100px;
  height: 100px;
  #child {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    @include onParentHover {
      transform: scale(1.2, 1.2);
    }
  }
}

The Final output

#parent {
  position: relative;
  width: 100px;
  height: 100px;
}
#parent #child {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
#parent:hover #child {
  text-size: 20px;
}