Sven
Sven

Reputation: 2889

Checked Checkbox opacity, rule is overriden even when declared after

I want to hide a checkbox by default and show a checkbox when it's selected, in the table-headd or the corresponding row is hovered:

.table td input[type=checkbox] {
    opacity: 0;
}

.table th input[type=checkbox], 
.table tr:hover input[type=checkbox], 
input[type=checkbox]:checked {
    opacity: 1;
}

When inspecting the result in Chrome Dev Tools, the second rule applies, but the opacity attribute is crossed out. I need to add an !important to get the desired result. Why is that?

Upvotes: 0

Views: 218

Answers (3)

Andrej Burcev
Andrej Burcev

Reputation: 353

You don't really need to use !important if you do an assigment as specific as the first one, so instead input[type=checkbox]:checked use .table td input[type=checkbox]:checked, this way css will apply the second rule, because it is as specific as the first rule:

.table td input[type=checkbox] {
    opacity: 0;
}

.table th input[type=checkbox], 
.table tr:hover input[type=checkbox], 
.table td input[type=checkbox]:checked {
    opacity: 1;
}

Upvotes: 1

Mitya
Mitya

Reputation: 34576

Because

.table td input[type=checkbox]

has more specificity than

input[type=checkbox]:checked

Specificity counts for more than the vertical order in which your rules are declared, hence the first rule wins out.

Upvotes: 0

Marcos Pérez Gude
Marcos Pérez Gude

Reputation: 22158

It's because the specifity of CSS. You can give more specifity to the rule to make it more important without !important sentence:

.table td input[type=checkbox] {
    opacity: 0;
}

.table th input[type=checkbox], 
.table tr:hover input[type=checkbox], 
.table tr td input[type=checkbox]:checked {
    opacity: 1;
}

How specifity works?

  • Inline style elements: 1000
  • IDs: 100
  • Tags: 10
  • Classnames and attributes: 1

If you make the sum, you'll obtain the specifity. The more specifity it's the rule applied.

Upvotes: 2

Related Questions