Rama Rao M
Rama Rao M

Reputation: 3071

Avoid css styles applying to child elements

Is there any way that parent tag styles do not apply to child tag elements?

I have to display some data so I wish to align them in table for better view. I want to apply some styles to the table to make it look good. I am using some additional components (like plugins) in my table. So if I do apply any style to tr tag of my table, those are applied to those components tags too, if they have tr tag. This should not happen...

Is there any way that I can avoid inheritance?

 <style>
 /*The plug-in component may have table tr tags.So the following styles should be applied to plug-in..*/
     table tr{
     background:#434334;
     border-radius:5px;
    }

</style>

Upvotes: 8

Views: 14639

Answers (2)

Jon
Jon

Reputation: 437854

CSS are meant to be inherited like that. If you want to "not inherit" you have a few options:

  1. Best: improve your selectors so that they only apply to the elements you need them to
  2. Good: if existing markup does not allow you to do the above, help by giving the element(s) that need to be styled an additional attribute (e.g. extra class) that allows you to improve the selectors
  3. Bad: write your selectors so that they apply globally, then write more selectors to "undo" the results on a case by case basis

In your case, it looks like a combination of the first two would work. You can give an id="foo" to your table and then change the selector to

table#foo > tbody > tr { /*...*/ }

The > is the child selector, which prevents the style from being applied to table rows further down the element tree.

Upvotes: 7

Barry Kaye
Barry Kaye

Reputation: 7759

One solution would be to name your style table tr.style1{ ... and then in each of your <tr>'s you could just add a class attribute, i.e. <tr class="style1">.

Upvotes: 2

Related Questions