问题
I want to alternate the background colour of a table to increase readability. After googling a bit I found the code I needed.
tr:nth-child(even) {
background-color: #000000;
}
The problem in my solution, I don't have access to head tag, and I want to implement this with inline style CSS, but it doesnt work.
<tr style="nth-child(even) background-color: #000000;">
Ideas?
回答1:
Inline styles are per-element, so you would have to inject the appropriate styles into the style
attribute of every other tr
element. If you're not already generating these rows dynamically, and you cannot use JavaScript to inject these styles, then you're stuck with having to manually apply the attribute on each tr
element.
回答2:
I had a similar situation. I solved it by putting a style section just before my table:
<style>
table#some_table_id tr:nth-child(even) { background-color:#dddddd; }
</style>
<table id="some_table_id">
<!-- table markup removed -->
</table>
Not the most elegant solution, but it works for me (in Google Chrome 29.0.x).
回答3:
In addition to BoltClock answer, if you can use jQuery you can try something like this:
$('tr:nth-child(even)').css("background", "red");
This auto-insert inline styles in your markup.
A working fiddle
回答4:
So, I am actually using React... I wanted to get a table to display the rows in alternating colors. The code uses a lot of inline styling and there are some interesting syntax differences for css, but I thought I would share the piece of code that does it.
I am mapping through an array of lines of a report:
<tbody>
<tr key={line.number} style={(line.number % 2) ? { backgroundColor: 'someColor' } : null}>
...code table column data here...
</tr>
</tbody>
I did find out that I cannot use this code; not because it doesn't work. Since there are lines that get skipped I still end up with rows of the same color next to each other. If I happen to figure that out I will update. For now, I guess I will just use borders.
-L-
回答5:
Here's what you're looking for, hope it helps.
tr:nth-child(even) {
background-color: black;
color: white;
}
tr:nth-child(odd) {
background-color: #0000335f;
}
<table class="table">
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>text1</td>
<td>text2</td>
<td>text3</td>
<td>text4</td>
<td>text5</td>
</tr>
</tbody>
</table>
来源:https://stackoverflow.com/questions/16171426/alternate-row-colours-on-tables-with-inline-style-css