Home > Back-end >  How do I shorten this CSS which has CSS Pseudo-elements using SCSS?
How do I shorten this CSS which has CSS Pseudo-elements using SCSS?

Time:02-08

How do I shorten this CSS which has CSS Pseudo-elements using SCSS?

.bar-color1 {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;
  
  &::after {
    color: #28A745;    
    content: url("../../assets/images/arrow.png");;
    display: inline-block !important;
    width: 0;
    height: 0;    
    position: absolute;
    right: 6px;
    top: -6px;    
  }       
}
.bar-color2 {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;
  
  &::after {
    content: "" !important;
  }         
}

As you can see both has these common styles

  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;

CodePudding user response:

I think it's better to have a parent class like bar like bellow:

.bar {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;

  &-color1::after {
    color: #28A745;    
    content: url("../../assets/images/arrow.png");;
    display: inline-block !important;
    width: 0;
    height: 0;    
    position: absolute;
    right: 6px;
    top: -6px;    
  }    

  &-color2::after {
    content: "" !important;
  }  
}

CodePudding user response:

You can use multiple selector:

.bar-color1, .bar-color2 {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;
}

CSS

.bar-color1, .bar-color2 {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;
}

.bar-color1 {
  &::after {
    color: #28A745;    
    content: url("../../assets/images/arrow.png");;
    display: inline-block !important;
    width: 0;
    height: 0;    
    position: absolute;
    right: 6px;
    top: -6px;    
  }       
}

.bar-color2 {
  &::after {
    content: "" !important;
  }         
}

CodePudding user response:

Use mixins:

@mixin customStyle {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;
}

Then use it like so:

.bar-color1 {
  @include customStyle();
}
.bar-color2 {
  @include customStyle();
}

More on mixins here.

  •  Tags:  
  • Related