This snippet doesn\'t work the way I expect:
As far as I can tell, no, you cannot differentiate between elements with or without a sibling text node using CSS alone:
div li span:first-child {
font-style: italic;
}
div li:first-child span {
font-weight: bold;
}
div li:empty span:first-child {
color:red;
}
div li span:only-child {
font-size: 20px;
}
<div>
<ul>
<li><span>This is a test</span></li>
<li>And <span>this is also a test</span></li>
<li><span>another test</span></li>
</ul>
</div>
Your code will apply the style to any span
element that is the first child of its parent. In both cases, your span
is the first child of its parent li
.
You don't want the first child span
in this case, you want the first child li
.
div li:first-child span {
font-weight: bold;
}
EDIT: I seem to have misunderstood your question, as it more relates to why the second span is bold, despite being preceded by text. As you presumed, text is not seen as a child element as the text node is technically part of its parent li
. Your code will work in the case of defined DOM siblings like other <div>
s or <span>
s, however I am not sure there's a sufficient way to say "If preceded by any text" without implementing javascript.
To not target the span if it's not the very first thing under its parent, just wrap the And
as follows:
<div>
<ul>
<li><span>This is a test</span></li>
<li><div style="display: inline: ">And</div> <span>this is also a test</span></li>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</ul>
</div>
You just have to twist your code a little:
div li:first-child span{
font-weight: bold;
}