【问题标题】:How do I shorten this CSS which has CSS Pseudo-elements using SCSS?如何使用 SCSS 缩短这个具有 CSS 伪元素的 CSS?
【发布时间】:2022-02-08 14:00:24
【问题描述】:

如何使用 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;

【问题讨论】:

    标签: css sass


    【解决方案1】:

    我认为最好有一个像 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;
      }  
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用多个选择器:

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

      【讨论】:

        【解决方案3】:

        使用mixins:

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

        然后像这样使用它:

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

        更多关于mixins here

        【讨论】:

          猜你喜欢
          • 2021-11-29
          • 1970-01-01
          • 2017-01-20
          • 2023-03-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多