简体   繁体   中英

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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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