csstwitter-bootstraphtml-tablebootstrap-5

How to change background color of table cell while using Bootstrap's CSS classes?


I am using Bootstrap 5.0 CSS and am trying to make a table with custom cell colors using some of my own CSS. The color property works fine, but when I try to change the background color using the background property, Bootstrap ignores the rule. Does anyone know how to fix this?

My code:

td.colorfy {
    background: blue;
    color: white;
  }
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"/>

<table class="table table-bordered">
  <tr>
    <td class="colorfy">cell</td>
    <td>cell</td>
    <td>cell</td>
  </tr>
</table>


Solution

  • Just use the !important directive to override any other behavior set by bootstrap. Have a look here for more information.

    td.colorfy {
        background: blue !important;
        color: white;
      }
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"/>
    
    <table class="table table-bordered">
      <tr>
        <td class="colorfy">cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
    </table>

    Or be more specific when setting your css rule:

    .table td.colorfy {
        background: blue;
        color: white;
      }
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"/>
    
    <table class="table table-bordered">
      <tr>
        <td class="colorfy">cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
    </table>

    As in bootstrap css the color is specified as:

    .table>:not(caption)>*>* {
        padding: .5rem .5rem;
        background-color: var(--bs-table-bg);
        border-bottom-width: 1px;
        box-shadow: inset 0 0 0 9999px var(--bs-table-accent-bg)
    }
    

    and that is more specific then your definition, it wins. By be more specific as bootstrap or using !important you can achieve the new background color.