Regin
Regin

Reputation: 13

add specificity to a div (Override existing CSS)

I have a site that uses CSS LESS. In order to override some of the CSS I have been told to add a little css specificity.

I have: <div class="rt-bg2"> in my code.

I have this CSS style I have found in firebug:

.main-bg-blue .rt-bg2 { background-image: url("../images/backgrounds/blue/top-bg-texture.png"); }

I want to override the setting, that outputs this image. So I understand that I have to add a css specificity. I have read articles about it, and believe I have a understanding of how it works, but I can´t make my override work.

Can anyone show me, in an example, how I can add a css specificity to the code above?

Thx Regin

(BTW I am using a template from rockettheme.com, where overriding the LESS files is done via creating custom.css files, where the code that should override the original files are placed.)

Upvotes: 1

Views: 1247

Answers (3)

Branislav
Branislav

Reputation: 221

You should definitely read these articles first before you start to dive into it.

Andy Clark on specificity

Html dog on specificity

Basic example based on your code. Example fiddle

<div id="grandparent">
    <div class="main-bg-blue">
        <div class="rt-bg2">&nbsp;</div>
    </div>
</div>


div {width:100px; height:100px} /* let us see the div how we want */



     #grandparent .rt-bg2 { background-image: url("http://dummyimages.com/100x100/000000/ffffff.png&text=dolor"); }
    .main-bg-blue .rt-bg2 { background-image: url("http://dummyimages.com/100x100/000000/ffffff.png&text=ipsum"); }
    /* .rt-bg2 { background-image: url("http://dummyimages.com/100x100/000000/ffffff.png&text=lorem"); } */

To be absolutely sure that your new rule will overwrite old one in your example, without adding classes or ID in your existing code, you should find parent element like in my example ID "grandparent" or class "grandparent" and set the rule with that class or ID included.

ID's have greater specificity then classes though.

#grandparent .main-bg-blue .rt-bg2 { background-image: url("http://some-other-image-or-similar"); }

This is of course one way to do it. It really depends on your html code, and etc.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Why don't you add

.main-bg-blue .rt-bg2 {
    background-image: url("<url of your image>");
}

to the custom css file if you want to apply the globally.

Or

Add an extra class like rt-bg2-special to the element like <div class="rt-bg2 rt-bg2-special">`, then add the following to the custom css file

.main-bg-blue .rt-bg2.rt-bg2-special {
    background-image: url("<url of your image>");
}

Upvotes: 0

NewInTheBusiness
NewInTheBusiness

Reputation: 1475

How about adding style="background-image: url("whatever");"

after class="rt-bg2" ?

Upvotes: 0

Related Questions