Kevin Kevin - 4 months ago 14
Sass (Sass) Question

Can I specify ID's on elements within a keyframe to reduce CSS using sass?

I'm sure this is somewhat of a newbie question, but I have just recently started implementing sass in my projects and I would like to know if there is an easier/more efficient way to make this code happen using sass - thanks for your help :) .

I want to group such that I can identify the 100% keyframe's width by ID instead of rewriting the animation line and the keyframe for each.

span.underline {
display:block;
width:calc(100% - 130px);
height:2px;
background-color:transparent;
position:absolute;
left:41px;
}

#topNav .dropdown-menu>li>a:hover > span.underline#acctInfo {
animation: acctInfo 0.3s ease-out forwards;
background: #FFF;
}

@keyframes acctInfo {
0% {
width:0;
}
100% {
width:calc(100% - 130px);
}
}

#topNav .dropdown-menu>li>a:hover > span.underline#replenish {
animation: replenish 0.3s ease-out forwards;
background: #FFF;
}

@keyframes replenish {
0% {
width:0;
}
100% {
width:calc(100% - 60px);
}
}

#topNav .navbar-nav>li>a:hover > span.underline#more {
animation: more 0.3s ease-out forwards;
background: #FFF;
}

@keyframes more {
0% {
width:0;
}
100% {
width:calc(100% - 65px);
}
}

Answer

It isn't easy, I find no way to extract the id selector. The most I have archieve is a mixin wich I passed the id name as an argument. I also try to get the id from $name variable to add inside the mixin and no need write in the selector but I get the selector twice (with and without id).

SASS

@mixin animation($name) {
  animation: $name 0.3s ease-out forwards;
  @keyframes #{$name} {
    0% {
      width: 0;
    }
    100% {
      @if $name=="replenish" {
        width: calc(100% - 60px);
      }
      @else if $name=="more" {
        width: calc(100% - 65px);
      }
    }
  }
}

#topNav .dropdown-menu>li>a:hover > span.underline#replenish {
  @include animation(replenish);
  background: #FFF;
}

#topNav .dropdown-menu>li>a:hover > span.underline#more {
  @include animation(more);
  background: red;
}

OUTPUT

#topNav .dropdown-menu > li > a:hover > span.underline#replenish {
  animation: replenish 0.3s ease-out forwards;
  background: #FFF;
}
@keyframes replenish {
  0% {
    width: 0;
  }
  100% {
    width: calc(100% - 60px);
  }
}
#topNav .dropdown-menu > li > a:hover > span.underline#more {
  animation: more 0.3s ease-out forwards;
  background: red;
}
@keyframes more {
  0% {
    width: 0;
  }
  100% {
    width: calc(100% - 65px);
  }
}