Reputation: 61596
I have the following code:
<div class="citation">
<span>some text
<span id="innerSpan">inner text</span>
some more text
</span>
</div>
I am trying to affect the outer span of a div with citation
class, but not the inner span:
.citation {
color:red;
}
.citation span {
color: yellow
}
I've tried :first-of-type, :nth-child, but nothing seems to work.
Upvotes: 0
Views: 710
Reputation: 62743
By selecting the first inner span you'll be selecting the nested span. This makes it difficult (or impossible) in CSS to style the outer span
but have the inner
span inherit from the 2nd parent.
One solution would be to apply the same styles to .citation
and #innerSpan
, and a different style to the first span
child, like this:
.citation,
#innerSpan {
color: red;
}
/* or you could use
/
/ .citation,
/ .citation > span > span {
/ color: red;
/ }
/
*/
.citation > span {
color: yellow;
}
<div class="citation">
<span>some text
<span id="innerSpan">inner text</span> some more text
</span>
</div>
Definitely not ideal, but a bit of JavaScript would do the trick, like this:
var inners = Array.from(document.querySelectorAll('.citation > span > span'));
inners.forEach(inner => {
inner.style.color = window.getComputedStyle(inner.parentNode.parentNode).color;
});
.citation {
color: red;
}
.citation > span {
color: yellow;
}
<div class="citation">
<span>some text
<span id="innerSpan">inner text</span> some more text
</span>
</div>
Upvotes: 5
Reputation: 105843
color is inherited by children, you need therefor a reset
.citation {
color:red;
}
.citation > span {
color: yellow
}
.citation > span span {
color: initial; /* or any color you choose */
}
<div class="citation">
<span>some text
<span id="innerSpan">inner text</span>
some more text
</span>
</div>
For infos
Snippet uses initial value : https://developer.mozilla.org/en-US/docs/Web/CSS/initial
The
initial
CSS keyword applies the initial value of a property to an element. It can be applied to any CSS property, including the CSS shorthand all.
If you want the inner text same color as .citation
, then add the selector to the rule
.citation,
.citation > span span {
color:red;
}
.citation > span {
color: yellow
}
<div class="citation">
<span>some text
<span id="innerSpan">inner text</span>
some more text
</span>
</div>
Upvotes: 2
Reputation: 2499
You could use a child selector >
like this:
.citation {
color: red;
}
.citation > span {
color: yellow
}
Only direct child elements are selected now. The >
selector looks only one level down the markup structure.
Have a look here: https://css-tricks.com/child-and-sibling-selectors/
Upvotes: 2