htmlcss

How to find last/first not empty child using only CSS?


Let's say I have this:

<div>
   <span>1</span>
   <span>2</span>
   <span>3</span>
   <span></span>
  <span></span>
</div>

and want to add comma to each non-empty element, besides the last non-empty one (Not last child). So from "1 2 3" I want to have "1, 2, 3".

Excluding last child is easy Fiddle But this last non-empty.


Solution

  • I'm pretty sure I've found the solution that works every time and in every possible case here: https://jsfiddle.net/4ktq3d3u/1 :)

    HTML

    <div>
        <span></span>
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span></span>
        <span>4</span>
        <span></span>
        <span>5</span>
        <span><span>
    </div>
    

    CSS

    span:not(:first-child):not(:empty)::before {
        content: ', ';
    }
    
    span:empty + span:not(:empty)::before {
        content: '';
    }
    
    span:not(:empty) ~ span:empty + span:not(:empty)::before {
        content: ', ';
    }