如何在使用 Bootstrap 的 CSS 类时更改表格单元格的背景颜色?

moo*_*ose 1 css html-table twitter-bootstrap bootstrap-5

我正在使用 Bootstrap 5.0 CSS,并尝试使用我自己的一些 CSS 制作一个具有自定义单元格颜色的表格。该color属性工作正常,但是当我尝试使用该background属性更改背景颜色时,Bootstrap 会忽略该规则。有谁知道如何解决这一问题?

我的代码:

td.colorfy {
    background: blue;
    color: white;
  }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Jar*_*sto 6

只需使用该!important指令来覆盖引导程序设置的任何其他行为。请查看此处了解更多信息。

td.colorfy {
    background: blue !important;
    color: white;
  }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

或者在设置 css 规则时更加具体:

.table td.colorfy {
    background: blue;
    color: white;
  }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

正如 bootstrap css 中的颜色指定为:

.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)
}
Run Code Online (Sandbox Code Playgroud)

这比你的定义更具体,它获胜。通过更具体地作为引导程序或使用!important您可以实现新的背景颜色。