简体   繁体   中英

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>

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 (eg 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.

一种解决方案是将样式table tr.style1{ ... ,然后在每个<tr> ,您都可以添加一个class属性,即<tr class="style1">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM