Use table row coloring for cells in Bootstrap

2019-03-11 23:31发布

Twitter Bootstrap offers classes to color table rows like so:

<tr class="success">

I like the color choice and the class naming. Now what I would like to do, is to re-use these classes and apply them on table cells, too. Obviously, I could define my own classes with the same colors and be done with it.

But is there a shorthand in CSS. LESS, to let the td inherit the classes?

5条回答
戒情不戒烟
2楼-- · 2019-03-11 23:58

You can override the default css rules with this:

.table tbody tr > td.success {
  background-color: #dff0d8 !important;
}

.table tbody tr > td.error {
  background-color: #f2dede !important;
}

.table tbody tr > td.warning {
  background-color: #fcf8e3 !important;
}

.table tbody tr > td.info {
  background-color: #d9edf7 !important;
}

.table-hover tbody tr:hover > td.success {
  background-color: #d0e9c6 !important;
}

.table-hover tbody tr:hover > td.error {
  background-color: #ebcccc !important;
}

.table-hover tbody tr:hover > td.warning {
  background-color: #faf2cc !important;
}

.table-hover tbody tr:hover > td.info {
  background-color: #c4e3f3 !important;
}

!important is needed as bootstrap actually colours the cells individually (afaik it's not possible to just apply background-color to a tr). I couldn't find any colour variables in my version of bootstrap but that's the basic idea anyway.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-03-12 00:04

With the current version of Bootstrap (3.3.7), it is possible to color a single cell of a table like so:

<td class = 'text-center col-md-4 success'>

查看更多
别忘想泡老子
4楼-- · 2019-03-12 00:08

Updated html for the newer bootstrap

    .table-hover > tbody > tr.danger:hover > td {
     background-color: red !important;
}
.table-hover > tbody > tr.warning:hover > td {
     background-color: yellow !important;
}
.table-hover > tbody > tr.success:hover > td {
     background-color: blue !important;
}
查看更多
Lonely孤独者°
5楼-- · 2019-03-12 00:20

Bottom line is that you'll have to write a new css rule for that.

Depending on which bundle of Twitter Bootstrap you're using, you should have variables for the various colours.

Try something like:

.table tbody tr > td {
  &.success { background-color: $green; }
  &.info { background-color: $blue; }
  ...
}

Surely there's a way to use extend or the LESS equivalent to avoid repeating the same styling.

查看更多
太酷不给撩
6楼-- · 2019-03-12 00:21

With less you can set it up like this;

.table tbody tr {
    &.error > td { background-color: red !important; }
    &.error:hover > td { background-color: yellow !important; }
    &.success > td { background-color: green !important; }
    &.success:hover > td { background-color: yellow !important; }
    ...
}

That did the trick for me.

查看更多
登录 后发表回答