Use .alt with table rows to have alternating colors

Hi,
I have this CSS

#checkout_page_container table.productcart tbody tr.product_row{color:#000000; background-color:#EAF2D3;}

it colors all the rows fine.
I want to add “alt” so that only every second row is colored.
I can not seem to get it right in this case.

This example at w3schools shows what I want to do
Tryit Editor v1.4

The first thing I would do would be to strip the selectors right back - including more than you need just leads to confusion and mistakes, as well as slowing your page down. You shouldn’t need more than [COLOR="DarkGreen"].productcart tbody tr {...}[/COLOR] at most. You can then put a second line in [COLOR="DarkGreen"].productcart tbody tr.alt {...}[/COLOR] with a different background colour. Then just add [COLOR="DarkGreen"]class="alt"[/COLOR] to every other <tr> and you’re done.

Hi welcome to Sitepoint :slight_smile:

As you have classes on all table-rows you have made this a little awkward and you would need to use a concatenated class like this.


tr.product_row{color:#000; background-color:#EAF2D3;}
tr.product_row.alt td{background-color:red;}

Which would refer to this structure:


<table cellspacing="0" cellpadding="0">
	<tr class="product_row">
		<td>1</td>
		<td >5</td>
		<td>6</td>
		<td>7</td>
	</tr>
	[B]<tr class="product_row alt">[/B]
		<td>2</td>
		<td>7</td>
		<td>5</td>
		<td>7</td>
	</tr>
	<tr class="product_row">
		<td>3</td>
		<td>7</td>
		<td>7</td>
		<td>7</td>
	</tr>
	[B]<tr class="product_row alt">[/B]
		<td>4</td>
		<td>5</td>
		<td>5</td>
		<td>5</td>
	</tr>
	<tr class="product_row">
		<td>5</td>
		<td>5</td>
		<td>5</td>
		<td>7</td>
	</tr>
</table>


That will be buggy in IE6 as it doesn’t like dot separated classes.

Also be careful with rules like this:


#checkout_page_container table.productcart tbody tr.product_row{color:#000000; background-color:#EAF2D3;}

That is much too long a path to be useful and will slow the browser down on a busy page not to mention it makes the code bulkier and harder to read and more prone to mistakes.

It is probably likely that you only need this:


.productcart tr {color:#000000; background-color:#EAF2D3;}

But does of course depend on what you have done before.