user3780848 user3780848 - 2 months ago 7
CSS Question

SASS multiple classes share same and different css

i have 3 html elements

<div id="top-bg-animate-0"></div>
<div id="top-bg-animate-1"></div>
<div id="top-bg-animate-2"></div>


both have same css

#top-bg-animate-0,
#top-bg-animate-1,
#top-bg-animate-2 {
position:absolute;
top:0; left:0;
width:100%;
bottom:-50%;
display:block;
background-size:cover;
background-position:top left;
background-repeat:no-repeat;
opacity:0;
}


and unique css too

#top-bg-animate-0 {
background-image:url(../images/level3.png);
transform:translateY(-20%);
-webkit-transform:translateY(-20%);
transition:opacity 1s, visibility 1s, transform 10s;
-webkit-transition:opacity 1s, visibility 1s, transform 10s;
}
#top-bg-animate-1{
background-image:url(../images/level2.png);
transform:translateY(-30%);
-webkit-transform:translateY(-30%);
transition:opacity 1s, visibility 1s, transform 9s;
-webkit-transition:opacity 1s, visibility 1s, transform 9s;
}
#top-bg-animate-2 {
background-image:url(../images/level1.png);
transform:translateY(-30%);
-webkit-transform:translateY(-30%);
transition:opacity 1s, visibility 1s, transform 6s;
-webkit-transition:opacity 1s, visibility 1s, transform 6s;
}


i want to write this in SAAS way maybe
mixins
will help me it in but i also don't know how to nest classes like
class1,class2,class3
I'm stuck help me out !

Answer

you can use this mixin, it accepts a map (list) of classes with their styles, and a common style for all of them

@mixin bg-animations($defs) {
  @if map-has-key($defs, common) {
    $common: map-get($defs, common);
    $defs: map-remove($defs, common);
    #{map-keys($defs)} {
      @each $key, $value in $common {
        #{$key}: $value;
      }
    }
  }
  @each $className, $styles in $defs {
    #{$className} {
      @each $key, $value in $styles {
        #{$key}: $value;
      }
    }
  }
}

you can use it like this:

$defs: (
  #top-bg-animate-0: (
   transition: (opacity 1s, visibility 1s, transform 10s),
   background-image:url(../images/level3.png),
   transform:translateY(-20%)
  ),
  #top-bg-animate-1: (
   transition: (opacity 1s, visibility 1s, transform 9s),
   background-image:url(../images/level2.png),
   transform:translateY(-30%)
  ),
  #top-bg-animate-2: (
    transition: (opacity 1s, visibility 1s, transform 6s),
    background-image:url(../images/level3.png),
    transform:translateY(-30%)
  ),
  common: (
    position:absolute,
    top:0,
    left:0,
    width:100%,
    bottom:-50%,
    display:block,
    background-size:cover,
    background-position: top left,
    background-repeat:no-repeat,
    opacity:0
  )
);

@include bg-animations($defs);
Comments