skip to Main Content

Let’s say I have two CSS classes:

.all {
    background-color: red;
    border: 5px solid black;
}

.some {
    background-color: blue;
}

Some HTML elements will have the attribute class="all some" (i.e. they will have both classes). In this case, I want the class some to override all (the element should appear blue, but still have a 5px black border). What is the most efficient way to do this, without using the !important keyword? I have used this for a while, and it works (notice the [class] specifier on the some rule):

.all {
    background-color: red;
    border: 5px solid black;
}

.some[class] {
    background-color: blue;
}

Is there a special "precedence" character in CSS made for situations like this?

Note: there is no guarantee that some will always come after all in the stylesheets.

2

Answers


  1. You can declare styles for elements with multiple classes. Like this

    .some {}
    .all {}
    .some.all {}
    

    The way it determines which to use is related to the specificity, also see this for more examples

    .all, .some {
        background-color: red;
        border: 5px solid black;
        margin: 5px 0;
    }
    
    .all.some {
        background-color: blue;
    }
    <div class="all">All</div>
    <div class="some">Some</div>
    <div class="all some">All/Some</div>
    Login or Signup to reply.
  2. For a better way than hacking the specificity, you need cascade layers.

    You can’t raise the precedence of .some, but you can lower the precedence of .all. Do this:

    .some {
        background-color: blue;
    }
    
    @layer {
      .all {
        background-color: red;
        border: 5px solid black;
      }
    }
    <p class="some all">Hello World</p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search