-1

I have following css

.red {
    color: red !important;
}
.yellow {
    color: yellow;
 }

In html

<div class="red">
    red
    <span class="yellow">override this</span>
</div>

How do I override child color from parent? I can't use inherit. I have a condition that red is shown otherwise yellow. Please help me.

Umair Farooq
  • 1,567
  • 10
  • 14
  • 3
    Use the selector `.red .yellow` and set it to the value you like – cloned Aug 24 '20 at 14:41
  • I can't update child. can I change css by only updating parent? – Umair Farooq Aug 24 '20 at 14:42
  • Have you tried this? https://stackoverflow.com/questions/21297085/want-to-override-child-element-css-property-by-parent-element – BlackList96 Aug 24 '20 at 14:43
  • Why can't you update the css? Unfortunately this is your only option unless you want to write some JavaScript. Which I won't recommend because it would have bad impact on performance – cloned Aug 24 '20 at 14:43
  • The selector worked thanks. I can update css but can't update the child. I can already using react – Umair Farooq Aug 24 '20 at 14:45

2 Answers2

2

Here is what I would suggest

Here is my html

<div class="red">
    red
    <span class="yellow">override this</span>
</div>

  <span class="yellow">this will be yellow</span>
  
  <span class="red">this will be red</span>

this is my css

.red .yellow {
    color: red !important;
}

.red  {
    color: red !important;
}

.yellow {
    color: yellow
 }

As you can see the yellow is overridden by red

Junior Cortenbach
  • 530
  • 1
  • 5
  • 22
0

The advantage of this answer is about not using !important attribute.

You can do it simply using CSS parent-child syntax, also combining the father to make it with the same CSS properties (in our case), like this:

.red, .red > .yellow {
    color: red;
}

.yellow {
    color: yellow;
 }
<div class="red">
    red
    <span class="yellow">override this</span>
</div>

<p>Should be <b class="red">red</b></p>

<p>Should be <b class="yellow">yellow</b></p>
xKobalt
  • 1,478
  • 2
  • 11
  • 19