简体   繁体   English

如何使用 nth-child inline 更改行的背景颜色?

[英]How can I change a row's background colour with nth-child inline?

I have the following table:我有下表:

 .table tbody tr:nth-child(4n+1), .table tbody tr:nth-child(4n+2) { background: rgb(247, 247, 247); }
 <div class="container"> <table class="table table-sm"> <thead class="thead-default"> <tr> <td>Column 1</td><td>Column 2</td> </tr> </thead> <tbody> <tr> <td>Column Data</td><td>Column Data</td> </tr> <tr> <td>Column Data</td><td>Column Data</td> </tr> <tr> <td>Column Data</td><td>Column Data</td> </tr> <tr> <td>Column Data</td><td>Column Data</td> </tr> <tr> <td>Column Data</td><td>Column Data</td> </tr> <tr> <td>Column Data</td><td>Column Data</td> </tr> <tr> <td>Column Data</td><td>Column Data</td> </tr> <tr> <td>Column Data</td><td>Column Data</td> </tr> </tbody> </table> </div>

I can change the background colour of the nth row with CSS by doing:我可以通过执行以下操作使用 CSS 更改第 n 行的背景颜色:

.table tbody tr:nth-child(4n+1),
.table tbody tr:nth-child(4n+2) {
    background: rgb(247, 247, 247);
}

How can I do the same by changing the style of the table inline?如何通过更改内联表格的样式来做同样的事情? I have tried to replace我试图更换

<table class="table table-sm">

with

<table style="tr:nth-child(4n+1){background: rgb(247, 247, 247)}; tr:nth-child(4n+2){background: rgb(247, 247, 247)}" class="table table-sm">

but it does not work.但它不起作用。 I am a bit confused about the correct syntax.我对正确的语法有点困惑。

An inline style relates only to the element in whose tag it is written (ie without a selector).内联样式仅与写入标签的元素相关(即没有选择器)。 You'd have to write the background definition into each single td to which it should apply...您必须将背景定义写入应应用的每个td ...

As an in-between solution (between external stylesheet and inline style), you can add a <style> tag to your HTML code and put the CSS rules in there.作为中间解决方案(在外部样式表和内联样式之间),您可以在 HTML 代码中添加<style>标记,并将 CSS 规则放在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM