CSS selector switch

I am trying to merge two CSS files from different vendors. The first defines

body.mine div {border:1px solid red} 

Second

 .blue-border {border:1px solid blue} 

In the generated HTML you can find

 <div class="blue-border">hello</div> 

It looks red, not blue. I canโ€™t change the HTML nor the first CSS code. My only hope is to change the second CSS. Any hints? Thank you very much!

Example:

 <html> <head> <style> body.mine div {border:1px solid red} .blue-border {border:1px solid blue} </style> </head> <body class="mine"> <div>hallo</div> <div class="blue-border">hello</div> <- looks red, not blue as I want </body> </html> 
+4
source share
4 answers

Just make the selector more specific:

 body.mine div.blue-border {border:1px solid blue} 

This tells the browser to look for a much more specific element: a div with a blue border class, which is a child of the body that my class has.

Just said โ€œselect everything that has a blue border classโ€ and it was less specific than the previous selector.

http://jsfiddle.net/Kyle_Sevenoaks/tcWK5/

+10
source

You need a selector more specific than a body.mine div, so that it overrides a less specific selector. Try something like:

 body.mine div.blue-border {border:1px solid blue} 
+3
source

It may also be ideal for !important .

 .blue-border {border:1px solid blue !important} 

I understand that using !important often frowned upon, but .blue-border is obviously a utility class that does only one thing, which means that the class should not be used if the intentional result is a red border.

In this case, I would prefer !important use a more qualified selector, because more qualified selectors can have a significant impact on performance.

+1
source

If you want to change a property in all elements using css, DO NOT define this property in certain elements:

 html body div#very .specific { /* Any prop that is NOT the ones you want to apply generally */ margin: ... font-weight: ... /* NOT color, nor background, etc */ } /* These now will catch in the above too */ .blue{ color: blue; } .back-yellow{ background: #ff0; } 

Explanation: The color and background will apply to all elements that do not have a more specific definition of color / background.

So, just define the color in a specific CSS path if you want to override the general rules.

0
source

All Articles