ftravers
ftravers

Reputation: 4009

css element style affecting the parent style

I have a <div> that contains a <button>. Each have their own classes. In the styles for each of those classes I specify the background-color property. For some reason the child button over-rides the parent property.

.tab {
  background-color: red;
}

.tab,
button.active {
  background-color: blue;
}
<div class="tab">
  <button>My Button</button>
  <button class="active">button 2</button>
</div>

Here is a JS Fiddle showing it:

https://jsfiddle.net/jp3kbfwn/

Upvotes: 0

Views: 121

Answers (3)

Oscar W
Oscar W

Reputation: 484

This is because you're listing your css elements rather than using selectors. Heres what the css should look like.

<style>
.tab {
    background-color: red;
}
.tab > button.active {
    background-color: blue;
}
</style>

Note how i've added in the > selector

Upvotes: 0

Rana Faiz Ahmad
Rana Faiz Ahmad

Reputation: 1698

The .tab element is getting the blue background because you're using a comma between .tab and button.active when defining their styles.

The comma in this context means apply to both of these elements.

Upvotes: 0

infused
infused

Reputation: 24367

Remove the comma after .tab:

.tab button.active {
    background-color: blue;
}

With the comma, it is saying to set the background color to blue for both the .tab class and button.active.

Upvotes: 3

Related Questions