Search code examples
htmlcss

CSS selectors, target an empty span but not span that has an <a> tag or tags in it


I have these two markup up patterns:

<h3>
    <span>Title</span>
    <span></span>
</h3>

and

<h3>
    <span>Title</span>
    <span><a>link</a><a>link</a></span>
</h3>

I want to target the former but not the latter with CSS and use ::after to insert a visual flourish. I prefer not to use a class. I just can't seem to get it!

h3>span+span:not(h3>span+span>a)::after {
    border: solid 1px transparent;
    content: '\2199';
    display: inline-block;
    color: gray;
}

Solution

  • Use :not(:has(*)) to select an empty element (more detail from my blog: https://css-tip.com/number-elements-has-selector/)

    h3 span:last-child:not(:has(*))::after {
      border: solid 1px transparent;
      content: '\2199';
      display: inline-block;
      color: gray;
    }
    <h3>
      <span>Title</span>
      <span></span>
    </h3>
    and
    
    <h3>
      <span>Title</span>
      <span><a>link</a><a>link</a></span>
    </h3>