Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tr:nth-child(even) help. how to apply to one class?

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  
like image 446
user190284 Avatar asked Oct 15 '09 01:10

user190284


People also ask

Does nth child work on class?

:nth-child() operates on an entire level of siblings without regard for any other simple selectors.

How do I select a specific Nth child in CSS?

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.

What does TR nth child even mean the style here will be?

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.

How do I select a specific child in CSS?

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.


3 Answers

Use the CSS descendant combinator (juxtaposition) as usual:

table.dashboardtable tr:nth-child(even)
table.dashboardtable tr:nth-child(odd)
like image 62
hobbs Avatar answered Oct 05 '22 21:10

hobbs


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

like image 41
Marius Avatar answered Oct 05 '22 20:10

Marius


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>
like image 31
Scott Avatar answered Oct 05 '22 22:10

Scott