【问题标题】:How to change background color of table cell while using Bootstrap's CSS classes?使用 Bootstrap CSS 类时如何更改表格单元格的背景颜色?
【发布时间】:2021-05-18 17:16:45
【问题描述】:

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

我的代码:

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>

【问题讨论】:

  • 我建议阅读the documentation for tables,因为那里有关于如何计算背景颜色的信息。您可能希望使用其中一个 Bootstrap 类来进行更改。

标签: css twitter-bootstrap html-table bootstrap-5


【解决方案1】:

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

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>

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

.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>

在 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)
}

这比你的定义更具体,它赢了。通过更具体的引导程序或使用!important,您可以获得新的背景颜色。

【讨论】:

  • 请注意该网站所说的:“此属性的所有后续定义都将被忽略”。因此,如果您稍后想更改该行的背景图像,则此答案中的 !important 将覆盖它。
  • 我的真实代码有很多规则,我不想手动添加!important
  • 然后使用我刚刚添加的更具体的定义
猜你喜欢
  • 2013-06-15
  • 1970-01-01
  • 2012-07-16
  • 2020-07-08
  • 1970-01-01
  • 2020-04-28
  • 2016-05-19
  • 2011-11-06
  • 1970-01-01
相关资源
最近更新 更多