Search code examples
cssshadow-dom

:last-child inside the Shadow DOM not working - Firefox?


Does anybody know the reason why the CSS selector :last-child doesn't work inside the Shadow DOM on Firefox? It works on Chrome as expected. I could not find any information on this. Thanks!


Solution

  • Try the :-moz-last-node property. It is not verified by W3C, so many would recommend against it, but I think it's your best bet if the :last-child pseudo-selector doesn't do the job. Use it like so:

    span:-moz-last-node {
      color: lime;
      background-color: #000;
    }
    <p>
      <span>This does not match.</span>
      <span>This matches!</span>
    </p>
    
    <p>
      <span>This doesn't match because it's followed by text.</span>
      Lorem ipsum...
    </p>

    If you try the snippet above, and you are not on Firefox, it will not work, as the pseudo-selector is for Mozilla browsers. If you want to see the effect in other browsers like Chrome and Edge, it would look like so:

    a:last-child {
      color: lime;
      background-color: #000;
    }
    <p>
      <a>This does not match.</a>
      <br />
      <br />
      <a>This matches!</a>
    </p>
    
    <p>
      <span>This doesn't match because it's not an "a".</span>
    </p>

    Again, if you are on Firefox, the first snippet will work (and maybe the second). But the second will work on all modern browsers (maybe excluding Firefox). Try this, if it works, please let me know. I'll fix it if there are any problems.

    You can learn more about the "un-verified" :-moz-last-node pseudo-selector here.