Dwarakesh Pallagolla
Dwarakesh Pallagolla

Reputation: 483

override a CSS class if two other classes are present

I want to override a CSS class if two other CSS classes are present for a particular element.

Eg:

<img class="class1 class2" />

I want to override class3 in this case.

I my current implementation is something like below.

.class1.class2 { .class3 {padding-left: 1px}  }

But this approach does not seem to work!

Upvotes: 1

Views: 2065

Answers (4)

connexo
connexo

Reputation: 56754

Just go

.class1.class2.class3 {
  /* these definitions are more specific and don't need !important; */
}

Remember this requires you to put class3 on the element as well:

<element class="class1 class2 class3"></element>

If the only reason you wanted to add class3 is to specify styles that should be applied when both classes class1 class2 are present, you don't even need class3, just go

.class1.class2 {
  /* these definitions are more specific than those for .class1 or .class2 
  and don't need !important;
  These rules apply to any element that has both class1 and class2 */
}

Upvotes: 4

duichwer
duichwer

Reputation: 177

Since you are showing us an image tag, I assume that class3 isn't nested inside this tag. An image-Tag shouldn't have nested elements. With you definition class3 would be an element inside another. For example:

 <p class="class1 class2"><span class="3">some text</span</p>

For your case it is necessary to define the class inside the same level.

.class1.class2 {
    &.class3 {
        padding-left: 1px
    }
}

The amper defines the class3 at the same level.

Since this definition is more specified than .class1.class2 it should override those styles.

Upvotes: 1

ca8msm
ca8msm

Reputation: 1210

You can't embed a selector inside another like you have done, however you can specify what should be used when both classes are present. e.g.

HTML

<p class="class1">A</p>
<p class="class2">B</p>
<p class="class1 class2">C</p>

CSS

.class1 {border:1px solid red}
.class2 {border:1px solid green}
.class1.class2 {border:1px solid blue}

https://jsfiddle.net/5zjznd8t/

Upvotes: 1

Deadpool
Deadpool

Reputation: 8240

Try this:

<html> 

<head> 

<style>
.class1{background:green;}
.class2{background:blue;}
.class1.class2{background:red}

</style> 

</head> 

<body> 

    <p class="class1"> This is a paragraph. </p> 

    <p class="class2"> This is a paragraph. </p> 

    <p class="class1 class2"> This is a paragraph. </p> 

</body> 

</html> 

Result:

enter image description here

Upvotes: 1

Related Questions