how to overwrite style on selector [] not using !important?

Viewed 33

I'm using UI Library(Vuetify) and this is the code it has:

 .sample[data-2] {
       color:red;
 }

and I want to overwrite all the elements having .sample classes like this:

   .sample {
        color:blue;
   }

If i use '!important' then it surely works, but I want better solution to overwrite .sample[blabla] class.

I've tried .sample[*], .sample[] ... it didn't work

1 Answers

You can increase the specificity of your CSS by including :not pseudo class with a # id name.

The id name needs to be one not used elsewhere.

div {
  margin: 10px;
}

.sample[data-2] {
  color: red;
}

.sample:not(#nonExistentId) {
  color: blue;
}
<h2>All these lines should be blue</h2>
<div class="sample">a div with class sample</div>
<div class="sample" data-2>a div with class sample and attribute data-2</div>
<div class="sample" anyoldattribute>a div with class sample and any old atrribute</div>

See MDN for a fuller explanation.

In particular if you need to support older browser versions you could use combinations of :is, :matches and so on.

Related