Bhakti Thakkar
Bhakti Thakkar

Reputation: 373

How to prevent CSS color property applied from parent class to child classes

I want to add CSS in child1 class using parent class name only. I tried this code but CSS is being added in all sub classes of child1. I don't want to add CSS in the sub classes of child1

.root .child1 {color: red;}
<div class="root">
  <div class="child1">Hi I am child1 of root
    <div class="child12">child2</div>
  </div>
</div>

Upvotes: 2

Views: 825

Answers (1)

Nithya Rajan
Nithya Rajan

Reputation: 4884

To prevent the child classes getting the parent class color, use the following CSS

.child1 * {
  color: black;
}

* selects all the elements which are children of the .child1

If you only want to prevent the direct child of the parent class you can use the following css

.child1 > * {
  color: black;
}

    .root .child1 {
 background-color: red;
}

.root .child1 div{
  background-color: white;
}
<div class="root">
  <div class="child1">Hi I am child1 of root
    <div class="child12">child2</div>
    <div class="child13">child3</div>
    <div class="child14">child4</div>
  </div>
</div>

Upvotes: 4

Related Questions