I would like to change the background color of a specif column in a HTML table. Is it possible to use a property to do it. I found the way to do it with rows.
tr.even {
background-color: white;
}
I would like to change the background color of a specif column in a HTML table. Is it possible to use a property to do it. I found the way to do it with rows.
tr.even {
background-color: white;
}
Why don't you try using the colgroup tag and combining that with the span attribute. that way if you have 3 columns for instance, you can do
<colgroup>
<col span="2" id="something">
<col id="something2">
</colgroup>
then you can style that whole column with css.
ex:
#something2 {background-color:red;}
If you are looking to style the background of a column, and not a row, you can try something like this (below). You'll need to change the selectors to match your HTML.
td:first-child { background-color: #ccc; }
Below is a link to a fiddle, along with a way to add classes via JS. There are many ways, but since you are dealing with columns, remember that the CSS is being applied to the same td
in each row you want to style.
For modern browsers, you could use the nth-child()
selector:
element:nth-child(1) {
background-color:...
}
Or if you wanted to use jQuery, use eq()
:
$(element).eq(0).css("background-color","...");
Note: the CSS nth-child
selector is 1-based while the jQuery eq
selector is 0-based.
You can use :even and :odd selector:
$( "table tr:even" ).css( "background-color", "white" );
$( "table tr:odd" ).css( "background-color", "red" );
If you want to target the column then use:
$('table tr > :nth-child(even)').css('background-color','white');
$('table tr > :nth-child(odd)').css('background-color','red');
If you want to use just HTML and css you have to give every div even and odd class respectively. then give different css in you css file for both even and odd class.
<tr class="even"></tr>
<tr class="odd"></tr>
<tr class="even"></tr>
tr.even {
background-color: white;
}
tr.odd {
background-color: black;
}
if you want more dynamic way ,mean don't give class manually jquery will serach and add even odd div and give them specific class
Use jquery
$('tr:odd').addClass("odd")
$('tr:even').addClass("even")
and your css will be like this
tr.even {
background-color: white;
}
tr.odd {
background-color: black;
}