Skip to content Skip to sidebar Skip to footer

Css Set Attribute To Element But Not To Descendants

Is there a way in pure CSS of changing the color of an item but not it's descendants? Let's say I have this category tree:
  • N

Solution 1:

If you can ensure that items with content are tagged with some class that includes contents and the ones with no content has not class. You can try this:

.has-contents {
  font-weight: bold;
  color: blue;
}
.sub-has-contents {
  color: blue;
}
.my-list:not([class*="contents"]) {
  color:red;
}
<ulclass="my-list sub-has-contents"><li>No content in this branch
    <ul><li>Empty leaf node</li></ul></li><li>No content in this one either</li><liclass="sub-has-contents">There is content in this branch (3 items)
    <ul><liclass="has-contents">There is some content is this leaf node (1 item)</li><liclass="has-contents">More content here (2 items)</li><li>Lorem ipsum</li></ul></li></ul>

Solution 2:

No, you cannot set a property so that it would be exempted from inheritance, except of course when the problem is not inherited by definition.

If you set e.g. color on an element, then this value will be inherited by all children of that element, unless they themselves have color set on them. This is part of the very idea of CSS cascade. You cannot prevent it; you can just adapt to it.

Thus, you would need to set the property to those descendants that should not inherit it. It needs to be set to a specific value; there is no way to skip levels in inheritance (e.g. make an element inherit from its grandparent and not from its parent).

Solution 3:

you want to keep in mind the order in which you place your css, like if you were painting on a canvas, you want to paint the background colors first, then add the foreground colors. in this case, your base color is green, so make all the li of .sub-has-contents green, and then make your specific ones blue:

http://jsfiddle.net/mvm542e5/4/

.sub-has-contentsli {
    color:green;
}
.sub-has-contents.has-contents {
    font-weight: bold;
    color: blue;
}
.sub-has-contents{
    color: blue;
}

Solution 4:

You could apply a selector to all descendant elements to negate the other style.

.sub-has-contents * {
  color:red;
}
.has-contents {
  font-weight: bold;
  color: blue;
}
.sub-has-contents {
  color: blue;
}
<ulclass="my-list sub-has-contents"><li>No content in this branch
    <ul><li>Empty leaf node</li></ul></li><li>No content in this one either</li><liclass="sub-has-contents">There is content in this branch (3 items)
    <ul><liclass="has-contents">There is some content is this leaf node (1 item)</li><liclass="has-contents">More content here (2 items)</li><li>Lorem ipsum</li></ul></li></ul>

Post a Comment for "Css Set Attribute To Element But Not To Descendants"