How to use CSS first-child but excluding text content

后端 未结 4 1778
渐次进展
渐次进展 2021-01-19 01:38

This snippet doesn\'t work the way I expect:

相关标签:
4条回答
  • 2021-01-19 02:00

    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>

    0 讨论(0)
  • 2021-01-19 02:08

    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.

    0 讨论(0)
  • 2021-01-19 02:13

    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>
    
    0 讨论(0)
  • 2021-01-19 02:17

    You just have to twist your code a little:

    div li:first-child  span{
      font-weight: bold;
    }
    
    0 讨论(0)
提交回复
热议问题