class overrule when two classes assigned to one div

前端 未结 5 586
情话喂你
情话喂你 2020-12-13 01:45

I was creating a

tag in which I wanted to apply two classes for a
tag which would be a thumbnail gallery. One class for its
5条回答
  •  忘掉有多难
    2020-12-13 02:12

    Multiple classes can be assigned to a div. Just separate them in the class name with spaces like this:

    Content

    This div will then match any style rules for three different class selectors: .rule1, .rule2 and .rule3.

    CSS rules are applied to objects in the page that match their selectors in the order they are encountered in the style sheet and if there is a conflict between two rules (more than one rule trying to set the same attribute), then CSS specificity determines which rule takes precedence.

    If the CSS specificity is the same for the conflicting rules, then the later one (the one defined later in the stylesheet or in the later stylesheet) takes precedence. The order of the class names on the object itself does not matter. It is the order of the style rules in the style sheet that matters if the CSS specificity is the same.

    So, if you had styles like this:

    .rule1 {
        background-color: green;
    }
    
    .rule2 {
        background-color: red;
    }
    

    Then, since both rules match the div and have exactly the same CSS specificity, then the second rule comes later so it would have precedence and the background would be red.


    If one rule had a higher CSS specificity (div.rule1 scores higher than .rule2):

    div.rule1 {
        background-color: green;
    }
    
    .rule2 {
        background-color: red;
    }
    

    Then, it would take precedence and the background color here would be green.


    If the two rules don't conflict:

    .rule1 {
        background-color: green;
    }
    
    .rule2 {
        margin-top: 50px;
    }
    

    Then, both rules will be applied.

提交回复
热议问题