How to specify the order of CSS classes?

前端 未结 3 1070
孤独总比滥情好
孤独总比滥情好 2020-12-02 08:40

I\'m a little confused about CSS and the class attribute. I always thought, the order in which I specify multiple classes in the attribute value has a meaning.

相关标签:
3条回答
  • 2020-12-02 09:20

    The order of classes in the attribute is irrelevant. All the classes in the class attribute are applied equally to the element.

    The question is: in what order do the style rules appear in your .css file. In your example, .basic comes after .extra so the .basic rules will take precedence wherever possible.

    If you want to provide a third possibility (e.g., that it's .basic but that the .extra rules should still apply), you'll need to invent another class, .basic-extra perhaps, which explicitly provides for that.

    0 讨论(0)
  • 2020-12-02 09:23

    This can be done, but you have to get a little creative with your selectors. Using attribute selectors, you can specify things like "begins with", "ends with", "contains", etc. See example below using your same markup, but with attribute selectors.

    [class$="extra"] {
      color: #00529B;
      border:1px solid #00529B;
      background-color: #BDE5F8;
    }
    [class$="basic"] {
      border: 1px solid #ABABAB;
    }
    input {display:block;}
    <input type="text" value="basic" class="basic"/>
    <input type="text" value="extra" class="extra"/>
    <input type="text" value="basic extra" class="basic extra"/>
    <input type="text" value="extra basic" class="extra basic"/>

    0 讨论(0)
  • 2020-12-02 09:26

    The order in which the attributes are overwritten is not determined by the order the classes are defined in the class attribute, but instead where they appear in the CSS.

    .myClass1 {color:red;}
    .myClass2 {color:green;}
    <div class="myClass2 myClass1">Text goes here</div>

    The text in the div will appear green, and not red; because .myClass2 is further down in the CSS definition than .myClass1. If I were to swap the ordering of the class names in the class attribute, nothing would change.

    0 讨论(0)
提交回复
热议问题