Using multiple classes in one element and specificity

后端 未结 4 980
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-12 12:30

Just wondering when you use multiple classes on the one element such as class=\"foo bar\" and those classes are setup as below:

.foo {
    margin-ri         


        
相关标签:
4条回答
  • 2021-02-12 12:41

    In addition, more "specific" class will override a more generic one:

    HTML:

    <div class="foo">
        <div class="bar">Hello World!</div>
    </div>
    

    With the following CSS:

    .foo .bar { margin-left:25px }
    .bar { margin-left:0px }
    

    Notice how the inner div still has 25px margin to the left?

    Also, read up on "!important" argument after providing the value:

    .bar { margin-left:0px!important }
    

    Check out

    0 讨论(0)
  • 2021-02-12 12:45

    Also, if you wish to target the element who has only both classes, you can use this syntax:

    <ul>
      <li class="foo first">Something</li>
      <li class="foo">Somthing else</li>
      <li class="foo">Something more</li>
    </ul>
    
    .foo {
      color: red;
    }
    .foo.first {
      color: blue
    }
    
    0 讨论(0)
  • 2021-02-12 12:51

    It works based on precedence within the CSS. Therefore the item to occur most recently will override any previous styles.

    CASE 1

    .foo  { background : red; }
    .bar  { background : blue; }
    

    class = 'foo bar' would be blue in this instance.

    CASE 2

    .bar  { background : blue; }
    .foo  { background : red; } 
    

    class = 'foo bar' would be red in this instance.

    Working Example

    0 讨论(0)
  • 2021-02-12 12:52

    A single class name carries the same weight. In such a scenario, the rule that is listed first will be overwritten by the second, and hence, the element will have margin-right: 0px;

    Here is a simple example using color instead of margin, because it's easier to visualize. The value specified in bar will be chosen by the browser.

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