4

how can I make a css style NOT affect children of that element

$<style type="text/css">
.parent {
background-color: #0F0;}
.child {
    background-color:#fff
}
</style>

<div class="parent">parent<div class="child">child</div>Parent2</div>

(that DOES affect) I know you can you the "<" to apply the style to only children of certain parents but how can the style ONLY be applied to one element?

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • You cannot "disable" or "turnoff" inhertiance in CSS. The best you could do is "negate" it such as if parent has color: red; than child will also be red. So on child you can set color: black; Only some, not all, CSS properties are inherited. – Jawad Jul 09 '11 at 16:31
  • @Jawad In this particular case, the `background-color` property value is *not* inherited ([it doesn't inherit](http://www.w3.org/TR/css3-background/#the-background-color)), so this issue is not about inheritance. – Šime Vidas Jul 09 '11 at 16:34
  • This might be informative: http://stackoverflow.com/questions/4481318/css-text-decoration-property-cannot-be-overridden-by-ancestor-element – Šime Vidas Jul 09 '11 at 16:36
  • @Sime Vidas: Great Catch. I need a break. Fresh eyes see clearer! – Jawad Jul 09 '11 at 16:42
  • 1
    Children should not be allowed near css – Djave Jul 04 '13 at 14:38

4 Answers4

4

Technically, your code doesn't apply/affect the style on the children. It just looks like it because of how the markup with css is rendered. So your "child" DIVs do not have #0F0 background color applied to them, but since they are transparent by default it may look like that.

Kon
  • 27,113
  • 11
  • 60
  • 86
2

By default, background-color is transparent. If I understand your question correctly, you are seeing the parent's background through the child's transparent one. The only way around this is to set the child's background to be the colour you want it to.

Bojangles
  • 99,427
  • 50
  • 170
  • 208
1

You can't, hence the name "cascading" stylesheets. You just have to override whatever property you don't want the child to inherit.

Nate B
  • 6,338
  • 25
  • 23
0

Actually it doesn't since the child elements all have a background of "none" which displays a see-thru color. To get around this you'll need to define a color for the child element that is not the same as the parent.

matsko
  • 21,895
  • 21
  • 102
  • 144