Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

custom css being overridden by bootstrap css

I am using Bootstrap 3 and I have a table showing some data. in this table I have applied some javascript for conditional formatting, in the event that a condition is met, I set the element's class to "red"

.red {
background-color:red;
color:white;
}

the elements HTML is as follows:

<td class="red">0</td>

I now have a conflict on odd rows the text color applies but the background color is overridden by the following css from bootstrap.

.table-striped > tbody > tr:nth-child(odd) > td,
.table-striped > tbody > tr:nth-child(odd) > th {
  background-color: #f9f9f9;
}

how can I resolve this conflict and assure that the red class takes presedence?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Specificity

Your issue is most likely regarding specificity. Chris Coyier has a great article on CSS specificity. I would also suggest you check out this handy specificity calculator.

Using that calculator, we can see that .table-striped > tbody > tr:nth-child(odd) > td has a specificity of 23. As such, to override that, any new rule needs to have a specificity of something equal to or greater than 23. .red is at 10, so that isn't going to cut it.

In this case, it should be as simple as matching the existing specificity, and then adding your class to it. .table-striped > tbody > tr:nth-child(odd) > td.red gives us a specificity of 33. As 33 is greater than 23, your rule should now work.

See a working example here: http://bootply.com/91756

!important

In general, you should never use !important unless you never want that rule to be overridden. !important is basically the nuclear option. I am moderately confident in saying that if you understand specificity, you should never need to !important to make a custom rule work properly in a framework like Bootstrap.

Update

After a bit of thought, the rule I provide here is probably a bit too specific. What happens if you want to higlight a cell on a table that isn't stripped? To make your rule a bit more global while still having enough specificity to work in stripped tables, I would go with .table > tbody > tr > td.red. This has the same specificity as the Bootstrap stripping, but will also work on tables that are not zebra stripped. Updated example is here: http://bootply.com/91760


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...