As shown in the image i want to apply different color to different rows and columns, not only to alternate ones
3 Answers
Check below examples.
- Add a
classto required row and apply styles as required. - Use
nth-childselector.
Using class
table {
border-collapse: collapse;
}
td {
border: 1px solid grey;
padding: 10px 20px;
}
tr.yellow {
background-color: yellow;
}
tr.green {
background-color: green;
}
tr.blue {
background-color: blue;
}
tr.red {
background-color: red;
}
<table>
<tr class="yellow">
<td></td>
<td></td>
<td></td>
</tr>
<tr class="red">
<td></td>
<td></td>
<td></td>
</tr>
<tr class="green">
<td></td>
<td></td>
<td></td>
</tr>
<tr class="blue">
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Using nth-child
table {
border-collapse: collapse;
}
td {
border: 1px solid grey;
padding: 10px 20px;
}
tr:nth-child(1) {
background-color: red;
}
tr:nth-child(2) {
background-color: green;
}
tr:nth-child(3) {
background-color: blue;
}
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
1 Comment
Khyati
will try it on rows and columns
You can define class for every row with different color or you can user :nth-child(n) pseudo class for every row
You could do something like this, create a random function which assigns random color to each row of the table.
Checkout a sample of that
function init(){
var elements = document.getElementsByClassName('trentries');
for(var i=0; i<elements.length; i++){
getRandomColor(elements[i]);
}
}
function getRandomColor(element) {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
element.style.background = color;
}
<body onload="init()">
<table class='table'>
<tr class='head'>
<th>Col1</th>
<th>Col2</th>
<tr>
<tr class='trentries'>
<td class='entries'>a</td>
<td class='entries'>a</td>
</tr>
<tr class='trentries'>
<td class='entries'>a</td>
<td class='entries'>a</td>
</tr>
<tr class='trentries'>
<td class='entries'>a</td>
<td class='entries'>a</td>
</tr>
<tr class='trentries'>
<td class='entries'>a</td>
<td class='entries'>a</td>
</tr>
</table>
<body>

classto each row and do the styling as necessary.