Jake Psimos
Jake Psimos

Reputation: 640

CSS style scope with rules within an ID

If I have a table with ID tableProducts and it's style is defined in products.css like this:

#tableProducts {
   border-collapse:collapse;
}

How do I format the CSS rule so that any td, tr, or p within tableProducts will inherit the CSS rules so that any other table with a different ID will not inherit the rules defined like so:

#tableProducts tr, td {
      text-align:center;
}

The text-align works properly however other tables on the page are applying the tr, td rules defined above.

I am aware that I could simply define a class for the elements <tr> and <td> to use, but I am trying to better my understanding of CSS.

Upvotes: 0

Views: 322

Answers (5)

Bounasser Abdelwahab
Bounasser Abdelwahab

Reputation: 132

The reason other tables inherit the styles is because the second selector after the comma targets all the <td> elements in the page, in other words you should limit the scope of your selector by prefixing it with #tableProducts, like so:

#tableProducts tr, #tableProducts td {
  text-align: center;
}

NOTE: it's a good practice to put each selector in a new line, this helps you a lot with clarity and makes your code much more readable, it's also a bad practice to use IDs in your CSS, use classes instead, also when trying to name your classes make sure they contain only lowercase letters, numbers and hyphens, so the best answer to your question would be:

.table-products tr,
.table-products td {
  text-align: center;
}

Hope it helped : )

Upvotes: 1

John Slegers
John Slegers

Reputation: 47091

You need to replace ...

#tableProducts tr, td {
      text-align:center;
}

... with ...

#tableProducts tr, #tableProducts td {
      text-align:center;
}

Explanation

Selector #tableProducts tr, td applies to all elements that match one of these two selectors :

  • #tableProducts tr
  • td

This means that selector #tableProducts tr, td will apply to ALL td elements.

Selector #tableProducts tr, #tableProducts td applies to all elements that match one of these two selectors :

  • #tableProducts tr
  • #tableProducts td

Replacing #tableProducts tr, td with #tableProducts tr, #tableProducts td therefore means that your selector no longer applies to all td elements, but only to td elements inside #tableProducts, which is what you're going for!

Upvotes: 1

CodeNinji
CodeNinji

Reputation: 110

#tableProducts tbody tr td{
   text-align:center;
}

Upvotes: -1

OneSneakyMofo
OneSneakyMofo

Reputation: 1289

https://jsfiddle.net/0qvm6tc6/

#tableProducts > tr, td {
          text-align:center;
    }

Upvotes: 0

Alfred
Alfred

Reputation: 21396

Try,

#tableProducts tr,#tableProducts td{
      text-align:center;
}

Upvotes: 0

Related Questions