I'm not very good with CSS and I need some help.
I have a table where i want every other row to be gray and the alternating rows to be white. but i only want it to happen on one particular table.
I added some code to my CSS:
tr:nth-child(even) {
background: #CCC;
}
tr:nth-child(odd) {
background: #FFF;
}
but the problem is that its affecting every table on my site. I haven't found any examples where it applies only to a certain class. Is that possible? I want it to apply only to:
table.dashboardtable
:nth-child() operates on an entire level of siblings without regard for any other simple selectors.
Definition and Usage The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
tr:nth-child(even) or tr:nth-child(2n) Represents the even rows of an HTML table: 2, 4, 6, etc. :nth-child(7) Represents the seventh element.
The CSS child selector has two selectors separated by a > symbol. The first selector indicates the parent element. The second selector indicates the child element CSS will style.
Use the CSS descendant combinator (juxtaposition) as usual:
table.dashboardtable tr:nth-child(even)
table.dashboardtable tr:nth-child(odd)
nth-child
and nth-of-type
accept odd
and even
as well as a formula like an+b
, where a
and b
are constants.
Usually you want to use nth-of-type
, which will only apply to the type you specify. That will leave out other elements. If you want every even tr to have that background color, then try:
tr:nth-of-type(2n){
background: #CCC;
}
tr:nth-of-type(2n+1){
background: #FFF;
}
More info on CSS Selectors
Hope this makes sense of it.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#customers tr:nth-child(even){
background-color:white;
}
#customers tr:nth-child(odd){
background-color:Lavender;
}
</style>
</head>
<body>
<p>In your markup define your table:</p>
<table id="customers"></table>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With