Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CSS first-child but excluding text content

Tags:

html

css

This snippet doesn't work the way I expect:

div li span:first-child {
  font-weight: bold;
}
<div>
  <ul>
    <li><span>This is a test</span></li>
    <li>And <span>this is also a test</span></li>
  </ul>
</div>

Both span elements are bold. I would have expected the 2nd one to not be bold, because it follows the plaintext "And ", but I guess :first-child doesn't consider text content to be a child.

Is there a way to differentiate these two situations, and select elements which are not preceded by any content or siblings?


To clarify: In my specific case, I want to make a <span> element in each <li> element bold, but only if it's right at the beginning of the <li> and not preceded by any text or other elements.

like image 833
Jason S Avatar asked Nov 09 '22 10:11

Jason S


1 Answers

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>
like image 102
worc Avatar answered Nov 15 '22 13:11

worc