Alternate row colors on tables with inline CSS

I want to change the background color of the table to increase readability. After a short search, I found the code that I need.

tr:nth-child(even) {
    background-color: #000000;
}

The problem is my solution, I do not have access to the head tag, and I want to implement this using the built-in CSS style, but it does not work.

<tr style="nth-child(even) background-color: #000000;">

Ideas?

+5
source share
4 answers

Inline styles are one element, so you will need to insert the corresponding styles into the attribute stylefor each other element tr. If you are not generating these lines dynamically yet, and you cannot use JavaScript to enter these styles, then you are delayed to manually apply the attribute to each element tr.

+8

. , :

<style>
    table#some_table_id tr:nth-child(even) { background-color:#dddddd; }
</style>
<table id="some_table_id">
    <!-- table markup removed -->
</table>

, ( Google Chrome 29.0.x).

+4

In addition to BoltClock's answer, if you can use jQuery, you can try something like this:

$('tr:nth-child(even)').css("background", "red");

This automatically inserts inline styles into your markup.

Working violin

+1
source

Here is what you are looking for, hope this 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>
Run code
0
source

All Articles