2

My HTML:

<div id="login-light" class="bg-green"></div>

My CSS:

#login-light {
    background-color: red;
}

.bg-green {
    background-color: green;
}

how can I make my element have the background color green when it has the class .bg-green? I know that the CSS of an id takes priority over a class. I want to try and do this without JavaScript.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Jim Peeters
  • 2,573
  • 9
  • 31
  • 53

2 Answers2

5

Add another selector that is more specific:

#login-light.bg-green {
    background-color: green;
}
The Process
  • 5,913
  • 3
  • 30
  • 41
  • 1
    Thanks , this was the simple solution I was looking for ! – Jim Peeters Mar 11 '16 at 17:32
  • 1
    i tried it before with a space in between , that was why it was not working – Jim Peeters Mar 11 '16 at 17:33
  • @JimPeeters Yes, a space indicates two separate elements in a parent -> child relationship – TylerH Mar 11 '16 at 17:38
  • 1
    @JimPeeters : For question "How can I select an element with multiple classes?", I wrote an overview of the different ways to combine different selectors. You might find it interesting -> http://stackoverflow.com/questions/1041344/how-can-i-select-an-element-with-multiple-classes/34911808#34911808 – John Slegers Mar 11 '16 at 17:38
1

You can go to HTMLDog to read up on specificity, a summary is a the bottom of the page. A id noted in CSS is more specific than a class.

Calculating Specificity

The actual specificity of a group of nested selectors takes some calculating. Basically, you give every ID selector (“#whatever”) a value of 100, every class selector (“.whatever”) a value of 10 and every HTML selector (“whatever”) a value of 1. Then you add them all up and hey presto, you have the specificity value.

p has a specificity of 1 (1 HTML selector) div p has a specificity of 2 (2 HTML selectors, 1+1) .tree has a specificity of 10 (1 class selector) div p.tree has a specificity of 12 (2 HTML selectors + a class selector, 1+1+10)

Community
  • 1
  • 1
Danielson
  • 88
  • 1
  • 8