S. Tea
S. Tea

Reputation: 121

CSS - color direct text only/ do not inherit to other child - classes

I know similar questions have already been asked at least a dozens of times (at least I found a dozen of them), but none of the many answers I found solved my problem.

I just want to color the text which is directly(!) inside these <h3> tags:

<div class="page-header">
  <h3> I want this green <div class="page-header-button-group">But not this</div></h3>
</div>

please note: I cannot change anything in the html. I tried this:

.page-header > h3:first-child{
  color:green;
}

But it sadly is not doing what I need.

Upvotes: 0

Views: 190

Answers (2)

SVSchmidt
SVSchmidt

Reputation: 6537

The problem is, that the default value for color is not specified and its value is inherited from the parent (see w3schools). That means, since you specified a color for the <h3> and the <div> has no other color rules, it will inherit the color from its parent.

The only solution is to reset the color with an extra rule for each child. h3:first-child > * (any element which is a direct child of the h3).

.page-header > h3:first-child{
  color:green;
}

.page-header > h3:first-child > * {
  color: #000;
}
<div class="page-header">
  <h3> I want this green <div class="page-header-button-group">But not this</div></h3>
</div>

If this is a common thing in your page, you may also think of a class, e.g.: .color-default { color: #000; } (propably adding !important). Then you can just define the div as <div class="default-color">.

Upvotes: 1

Gerard
Gerard

Reputation: 15786

This should help you.

h3 {
  color: green;
}

h3>* {
  /* all children of h3 */
  color: black;
}
<div class="page-header">
  <h3> I want this green
    <div class="page-header-button-group">But not this</div>
  </h3>
</div>

Upvotes: 1

Related Questions