如何使用 SCSS 缩短具有 CSS 伪元素的 CSS?

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

如何使用 SCSS 缩短具有 CSS 伪元素的 CSS?

.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;
  }         
}

如您所见,两者都有这些共同的风格

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

您可以使用多个选择器:

.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;
  }         
}

使用mixins:

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

然后像这样使用它:

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

有关 mixin 的更多信息 here

我认为最好有一个 parent class 像 bar 像下面这样:

.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;
  }  
}