【问题标题】:How to simply CSS class with same properties except one property如何简单地使用除一个属性外具有相同属性的 CSS 类
【发布时间】:2021-07-10 02:25:04
【问题描述】:

我正在开发一个反应网络应用程序,它有 2 列作为 leftCol 和 rightCol 类名。两个类具有几乎相同的属性,但 z-index 不同。以下是样式

&__rightCol {
​ position : relative;
 ​box-sizing: border-box;
 ​z-index: 0;

 ​&_box {
  ​display : none;
  ​}
}

&__leftCol {
  position : relative;
  box-sizing: border-box;
  z-index: 1;

  &_box {
   display : none;
   }
}

如何简化这两个类,以便我们使用除 z-index 不同之外的通用类

【问题讨论】:

    标签: css reactjs styles less bem


    【解决方案1】:

    看起来你正在使用 SASS/SCSS?

    你可以使用@mixin

    @mixin col {
      position : relative;
      box-sizing: border-box;
    
      &_box {
        display : none;
      }
    }
    
    .rightCol {
      @include col;
    
      z-index: 0;
    }
    
    .leftCol {
      @include col;
    
      z-index: 1;
    }
    

    或者,如果您使用 CSS-in-js 框架,如 styled-components 或情感,您可以编写如下内容:

    const colStyles = (zIndex = 0) => css`
      position : relative;
      box-sizing: border-box;
      z-index: ${zIndex};
    
      &_box {
        display : none;
      }
    `;
    
    
    const StyledDiv = styled.div`
      &__rightCol {
        ${colStyles(0)};
      }
    
      &__leftCol {
        ${colStyles(1)};
      }
    `
    

    更新:减少

    .col {
      position : relative;
      box-sizing: border-box;
    
      &_box {
        display : none;
      }
    }
    
    .rightCol {
      .col();
      z-index: 0;
    }
    
    .leftCol {
      .col();
      z-index: 1;
    }
    

    【讨论】:

    • 它的文件更少,所以不是 @mixin ?应该用什么
    • 我已经更新了我的答案,你可以看看
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多