How to reuse styles?

前端 未结 9 1462
孤城傲影
孤城傲影 2021-02-12 14:36

Back in the past I learned a lot about CSS but now I can\'t remember how to reuse styles.

Example:

I have some tabs with class tab and I can switch

相关标签:
9条回答
  • 2021-02-12 15:06

    This selector inheritance is a nice feature of SASS.

    If you want to stick with plain CSS, look at the section on Selector Inheritance and you can see how the SASS code, with the @extend, is turned into regular CSS.

    0 讨论(0)
  • 2021-02-12 15:07

    Do this. Combine the styles and separate with a comma. Then add other rules targeting the differences.

    .tab, .active {
        position: relative;
        top: 0;
        left: 0;
        width: 100%;
        padding: 15px 0 15px 0;
        border: solid thin #CCC;
        text-align: center;
        font-weight: bold;
        margin-bottom: 10px;
        color: #272F42;
    }
    
    .tab{
        cursor: pointer;
        background-color: white;
    }
    
    .active {
        cursor: default;
        background-color: #FFCF75;
    }
    

    EDIT

    Based on your comment

    I'm currently switching the tabs by adding .active style to the class attribute.

    this is what I would do:

    HTML

    <div class="tab"></div>
    

    CSS

    .tab {
        position: relative;
        top: 0;
        left: 0;
        width: 100%;
        padding: 15px 0 15px 0;
        border: solid thin #CCC;
        text-align: center;
        font-weight: bold;
        margin-bottom: 10px;
        color: #272F42;
        cursor: pointer;
        background-color: white;
    }
    
    .active {
        cursor: default;
        background-color: #FFCF75;
    }
    

    Then just add or remove the .active class, leaving the .tab as is.

    As long as .active is lower down in the stylesheet, it will overwrite the necessary bits.

    0 讨论(0)
  • 2021-02-12 15:10
    1. You can extract base class with identic styles and mark your elements with two classes: .tab .base
    2. You can use dynamic css language as sass or less which supports classes inhritance
    0 讨论(0)
  • 2021-02-12 15:11

    Change the .tab rule to .tab, .active.

    0 讨论(0)
  • 2021-02-12 15:14

    Use both class names in the class attribute. In the .active rule, define only different styles like you have already in the second example.

    <div class="tab active"></div>
    
    0 讨论(0)
  • 2021-02-12 15:24

    You can combine .active into .tab and override the parts that need to change like this:

    .tab, .active {
        position: relative;
        top: 0;
        left: 0;
        width: 100%;
        padding: 15px 0 15px 0;
        border: solid thin #CCC;
        text-align: center;
        font-weight: bold;
        margin-bottom: 10px;
        color: #272F42;
        cursor: pointer;
        background-color: white;
    }
    
    .active {
        cursor: default;
        background-color: #FFCF75;
    }
    
    0 讨论(0)
提交回复
热议问题