Home > Software engineering >  CSS Specificity Order
CSS Specificity Order

Time:03-23

I have two css classes in a codebase and I'm unsure why one is being chosen over the other, I thought the specifity of my second one was stronger. Is anyone able to explain?

The CSS class that it's choosing is -

td, th, table { border-collapse: collapse; border: 1px solid #999; }

And the CSS that I want it to use is -

table.cancellation { border: none; }

I thought as the second one had a class selector it would have a stronger specificity, why am I wrong?

CodePudding user response:

You're overwriting the style for the table, but not the cells.

In the first table, everything has a red border.

In the second table, the table has a blue border, but since border-collapse:collapse is set, the red of the td & td appear above it.

In the third table, border-collapse is set to separate and you can see that the table does truly have a blue border.

In the last table, the styles for td and th are also overwritten - giving a borderless table.

th,
td,
table {
  border-collapse: collapse;
  border: 1px solid red;
  margin-bottom:1rem;// just for looks
}
table.table {
  border-color: blue
}

table.separate{
border-collapse:separate;
}

table.none,
table.none th,
table.none td{
border:none
}
<table>
  <tr>
    <th>
      Head
    </th>
    <td>
      cell
    </td>
</table>

<table class = "table">
  <tr>
    <th>
      Head
    </th>
    <td>
      cell
    </td>
</table>

<table class = "table separate">
  <tr>
    <th>
      Head
    </th>
    <td>
      cell
    </td>
</table>

<table class = "table none">
  <tr>
    <th>
      Head
    </th>
    <td>
      cell
    </td>
</table>

CodePudding user response:

CSS reads from top to bottom if the class td, th, table { border-collapse: collapse; border: 1px solid #999; } is written after

table.cancellation {     border: none;    }

Then it will take the properties of the one that comes at the very last in your code!

If this isn't the case then you can use "border: none !important" as it has the highest rank among everything else

In case both of these methods don't work then I suggest you show me the bigger picture as in type in your related HTML and complete CSS of the div

  •  Tags:  
  • css
  • Related