简体   繁体   中英

How to simply CSS class with same properties except one property

I am working on a react web app, which has 2 columns as leftCol and rightCol className. Both class have almost same property with z-index difference. following is the styling

&__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;
   }
}

how to simply these both classes, such that we use common class except z-index different

looks like you're using SASS/SCSS?

you can use @mixin

@mixin col {
  position : relative;
  box-sizing: border-box;

  &_box {
    display : none;
  }
}

.rightCol {
  @include col;

  z-index: 0;
}

.leftCol {
  @include col;

  z-index: 1;
}

or if you're using css-in-js framework like styled-components or emotion, you can write something like this:

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)};
  }
`

Update: Less

.col {
  position : relative;
  box-sizing: border-box;

  &_box {
    display : none;
  }
}

.rightCol {
  .col();
  z-index: 0;
}

.leftCol {
  .col();
  z-index: 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM