Style every other element with CSS

HTML CSSStyling your webpages with CSS is mostly quite basic. Still, sometimes you may be looking for a more challenging task. One I hadn’t had before was styling every other element in CSS. So in essence, I wanted to add a styling to the even or odd elements that occurred in HTML.

To exemplify this, let’s say you want to colour all the odd rows in a table. You could add styling manually to each of the odd rows, but that would not be satisfying solution. Instead, the answer you are looking for are CSS pseudo-classes. The syntax of such a pseudo-class looks like this:

 selector:pseudo-class { property: value; }

In our example, we want to use :nth-child(odd). For our table, if we want to give every other row a different background-color, this becomes:

<table>
	<tr>
		<td>Example 1</td>
		<td>Example 2</td>
	</tr>
	<tr>
		<td>Example 3</td>
		<td>Example 4</td>
	</tr>
	<tr>
		<td>Example 5</td>
		<td>Example 6</td>
	</tr>
	<tr>
		<td>Example 7</td>
		<td>Example 8</td>
	</tr>
	<tr>
		<td>Example 9</td>
		<td>Example 10</td>
	</tr>
	<tr>
		<td>Example 11</td>
		<td>Example 12</td>
	</tr>
</table>
tr:nth-child(odd) {
	background-color: #eee
}

This would become:

Example 1Example 2
Example 3Example 4
Example 5Example 6
Example 7Example 8
Example 9Example 10
Example 11Example 12

The table background colour as shown above is white, except for the odd rows, they are coloured.

 

Author Bio

Thank you for your interest in my blog! On this miniblog, I write mostly short (technical) blog posts that might interest other people. Read more about me or feel free to contact me.

 

Leave a Reply

Your email address will not be published. Required fields are marked *