user3225796
user3225796

Reputation: 269

Want to override child element css property by parent element

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

In CSS, "child" class has its own bg color, that I can't change. I want to apply "parent" class bg color to container. So, Is there any CSS trick to override "child" bg color by "parent" bg color.

Any help would be much appreciated.

Upvotes: 26

Views: 72272

Answers (3)

Marcatectura
Marcatectura

Reputation: 1695

You could override the CSS using jQuery, although it's inelegant. So, if you have HTML

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

and CSS:

.parent {
    width: 100px;
    height: 100px;
    background: red;
}
.child {
    width: 50px;
    height: 50px;
    background: blue;
}

this jQuery will find the parent background color and apply it to the child:

$('.child').on('click',  function(event) {
    var bg = $(this).parent().css("background-color"); // finds background color of parent
    $(this).css("background-color", bg);  //  applies background color to child
});

Here's a jsfiddle: link

Upvotes: 0

rvighne
rvighne

Reputation: 21877

.parent .child {
    background-color: inherit !important; // can also use "transparent"
}

Use !important only if nothing else works.

Upvotes: 3

Cam
Cam

Reputation: 1902

!important will override any inline background color applied, let me know if this works

.parent > .child {
    background-color: transparent !important;
 }

Upvotes: 21

Related Questions