WoJ
WoJ

Reputation: 29997

How to force !important from a parent element?

I would like to force a specific attribute on children elements, from the level of the parent. I thought that using !important would be enough, but it is not taken into account on children elements:

.up {
  color: red !important;
}

.down {
  color: blue;
}
<div class="up">
  <div class="down">
    this text should be red
  </div>
</div>

Is it possible to cascade !important down to the children elements?

Upvotes: 0

Views: 1025

Answers (6)

Mr Lister
Mr Lister

Reputation: 46579

If you can change the CSS anyway, you can do this without needing !important.

.up {
  color: red;
}

:not(.up) > .down {
  color: blue;
}
<div class="up">
  <div class="down">
    this text should be red
  </div>
</div>
<div class="down">
  this text should be blue
</div>

Upvotes: 0

Navneet Kumar
Navneet Kumar

Reputation: 671

<div class="up myclass">
  <div class="down">
    this text should be red
  </div>
</div>

.up {
  color: red !important;
}
.down {
  color: blue;
}
.myclass .down {color:initial; color:inherit;}

Whenever you have this kind of situation if you are working other person's code then never edit the initial code because you never know what that code is working for. In this situation you need to do is create your own class and edit the children with your own class.

Upvotes: 0

Manikandan2811
Manikandan2811

Reputation: 841

If u add the html like below the code and ur css will be correct..

HTML:

<div class="up">
  this text should be blue
  <div class="down">
    this text should be red
  </div>
</div>

Or Do u want the reverse color then, change the css code

css

.up {
  color: blue !important;
}
.down {
  color: red;
}

Upvotes: 0

Johannes
Johannes

Reputation: 67778

You can do the following:

.up > * {
  color: red !important;
}

This will affect all direct child elements. (You could probably erase the !important in this case, but that depends on the order of the rules and on theselector specifity of the rules for the child elements)

If you want to apply it to ALL children (not just the direct ones), use it without the >, like

.up * {
  color: red !important;
}

.down {
  color: blue;
}
.up > * {
  color: red;
}
<div class="up">
  <div class="down">
    this text should be red
  </div>
</div>

Upvotes: 2

vaishali
vaishali

Reputation: 19

.up > .down {
  color: red;
}

.down {
  color: blue;
}

Upvotes: 0

Vintage Coders
Vintage Coders

Reputation: 162

Please try this

.up>.down {
    color: red;
 }

I hope this is the solution that what you looking for.

Upvotes: 0

Related Questions