Target elements with multiple classes, within one rule

后端 未结 2 767
孤独总比滥情好
孤独总比滥情好 2020-12-22 16:55

I have some HTML that would have elements with multiple classes, and I need to assign them within one rule, so that the same classes could be different within different cont

相关标签:
2条回答
  • 2020-12-22 17:29

    Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.

    The following:

    .blue-border, .background {
        border: 1px solid #00f;
        background: #fff;
    }
    

    is for when you want to add styles to elements that have either the blue-border or background class, for example:

    <div class="blue-border">Hello</div>
    <div class="background">World</div>
    <div class="blue-border background">!</div>
    

    would all get a blue border and white background applied to them.

    However, the accepted answer is different.

    .blue-border.background {
        border: 1px solid #00f;
        background: #fff;
    }
    

    This applies the styles to elements that have both classes so in this example only the <div> with both classes should get the styles applied (in browsers that interpret the CSS properly):

    <div class="blue-border">Hello</div>
    <div class="background">World</div>
    <div class="blue-border background">!</div>
    

    So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.

    0 讨论(0)
  • 2020-12-22 17:30

    .border-blue.background { ... } is for one item with multiple classes.
    .border-blue, .background { ... } is for multiple items each with their own class.
    .border-blue .background { ... } is for one item where '.background' is the child of '.border-blue'.

    See Chris' answer for a more thorough explanation.

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