user893970
user893970

Reputation: 899

Forcing child divs to use parent's style

I wanted to give all of the child's div elements a background-color of parent div. But, as I see, child divs' style overwrite parent's style even though child's did not have that property. For example,

<!-- Parent's div -->
<div style="background-color:#ADADAD;">
    some codes here...
    <!-- child's div -->
    <div style="position:absolute;font-size:12px; left:600px;top:100px;">
        again some codes...
    </div>
</div>

In here, If i delete the style of child div, it works fine. I think my problem may be solved if i did the same thing with external css file also. But, I have already done hundreds of divs exactly like this. So, is there anyway to force parent's style to child style, just for background-color?(new in css)

Upvotes: 14

Views: 35468

Answers (3)

Hossein
Hossein

Reputation: 4137

Use css selectors like this to make the background of child div's inherit from their parent:

Parent's div
<div id="thisparticulardiv">
some codes here...
child's div
<div class="childrendiv">
again some codes...
</div></div>

CSS:

#thisparticulardiv {
    background-color:#ADADAD;
    ...
}

#thisparticulardiv div {
    background: inherit;
    position:absolute;
    font-size:12px;
    left:600px;
    top:100px;
}

Upvotes: 5

Kraz
Kraz

Reputation: 7100

Use the inherit property on the child div :

background:inherit

<div style="position:absolute;font-size:12px; left:600px;top:100px; background:inherit">

Upvotes: 2

Quentin
Quentin

Reputation: 944527

But, as i see, chid divs' style overwrite parent's style even though child's did not have that property.

No, they just don't inherit the value by default, so they get whatever value they would otherwise have (which is usually transparent).

You can (in theory) get what you want with background-color: inherit. That has problems in older versions of IE though.

Upvotes: 8

Related Questions