Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing child divs to use parent's style

Tags:

html

css

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)

like image 489
user893970 Avatar asked Sep 22 '11 16:09

user893970


2 Answers

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;
}
like image 121
Hossein Avatar answered Sep 17 '22 15:09

Hossein


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.

like image 33
Quentin Avatar answered Sep 20 '22 15:09

Quentin