HTML and CSS

How to set alternate table row color using CSS

The :nth-child() CSS pseudo-class matches the elements based on their position in a group of siblings. The :first-child(), :last-child() selector used to set the alternate background row color using CSS.

  1. odd: It represents the elements whose position is odd in a series: 1, 3, 5, etc.
  2. even: It represents the elements whose position is even in a series: 2, 4, 6, etc.

Syntax:

element:nth-child(even)

element:nth-child(odd)

Below are the example of odd rows of an HTML table and even rows of an HTML (Even and odd rules) CSS table with alternating color rows

how to set alternate table row color using css
Set alternate table row color using CSS
table {        
	border: 1px solid #CCCCCC ;
	@include border-radius(0.5rem);
	tr {
		
		&:nth-child(odd){
			background: #fff;
		}
		&:nth-child(even) {
			background: #f4f5fa;
		}
		td {                
			border-top: 1px solid #d7d7d8;   
			padding-top: 15px;
			padding-bottom: 15px;
			padding-left: 15px;
			padding-right: 15px;
			font-size: 16px;
			font-weight: 500;
			color: #3F3F3F;
		}
	}
	tr:first-child td{
		border-bottom: 3px solid #bc995c;
		font-size: 18px;
		font-weight: bold;
		padding-top: 10px;
		padding-bottom: 10px;
	}
}

--------------------------------------------------

div#test > *:nth-child(3n+1) {
	color: #CB000F;
}

div#test div:nth-of-type(5n+2) {
	background-color: #9999ff;
}

How to style table rows differently by CSS nth-child selector?

To matches all the even rows of the table and all the odd rows of the table use :nth-child() selector to set alternate table row color using CSS. Set alternate table row background color for improve the readability of large tables. It’s easily separation way of row using background color use of element:nth-child(even) and element:nth-child(odd) selector. CSS even and odd rules matches the exactly those elements in tables and lists which want to apply some CSS for differentiation to each row and lists and give the more styles to the tables using CSS. To add style to specific rows, columns, lists groups use the :nth-child() selector in your CSS. See the examples above where use of odd, even and other numbers in the nth-child selector.

You can customize this code further as per your requirement. Set alternate table row background color using CSS.


Learn HTML/CSS from W3 School Website