Fix CSS in Vue3 Component to display the latter selector's style without !important

I’m writing CSS for a Vue3 component and I can’t get one selector to override another. The element I’m targeting has the .in-selected-row, .in-selected-col, .in-selected-box and .selected-cell classes, but I only want to apply the styles from the second selector.

I would think that the second selector would have more specificity than the first, but the only way I’ve been able to get it to work is by adding the !important property.

Here is the code:

.in-selected-row.in-selected-box, .in-selected-col.in-selected-box {
  background-color: rgba(0, 128, 128, .25);
}

table tbody tr td.selected-cell {
  background-color: rgba(255, 0, 0, .25);
}

Here is the element I’m targeting:

<table><tbody>...<tr>...<td data-v-b4e148ca="" class="selected-cell in-selected-row in-selected-col in-selected-box"><input data-v-b4e148ca="" readonly="" class="sudoku-input"></td>...</tr>...</tbody><table>

Here is the CSS I’m seeing in the browser:

.in-selected-row.in-selected-box[data-v-b4e148ca], .in-selected-col.in-selected-box[data-v-b4e148ca] {
  background-color: rgba(0, 128, 128, 0.25);
}
table tbody tr td.selected-cell[data-v-b4e148ca] {
  background-color: rgba(255, 0, 0, 0.25); <- striked through
}

>Solution :

Let’s have a look at CSS specificity weight for the given selectors:

selector ids class type specificity
.in-selected-row.in-selected-box[data-v-b4e148ca] 0 3 0 0-3-0
.in-selected-col.in-selected-box[data-v-b4e148ca] 0 3 0 0-3-0
table tbody tr td.selected-cell[data-v-b4e148ca] 0 2 4 0-2-4

Comparing specificity columns goes from left to right, until one column value exceeds the one of the other. So between 0-3-0 and 0-2-4, the second column will decide and 0-3-0 wins.

So you need to add another class to your selector to have specificity decided on the third column, or add two classes, something like:

table tbody tr td.in-selected-row.selected-cell[data-v-b4e148ca] /* 0-3-4 */
.in-selected-row.selected-cell.selected-cell[data-v-b4e148ca]    /* 0-4-0 */

(I obviously don’t know exactly what the classes mean, so check which ones work for you)

Leave a Reply