Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pseudo-elements on SVG sub-elements

Tags:

html

css

svg

I currently have an SVG which is a map of the UK, I've added some circle elements to the SVG which will be used as location markers.

<circle id="newcastle" cx="123.79" cy="152.28" r="2" fill="#ff671f"></circle>

Ideally, I was hoping to use the selector

#newcastle:hover::after { ... }

to create a pseudo-element when the user hovers over the location marker, but this doesn't appear to be working.

I've had a look online but most articles seem to be related to using SVGs in pseudo-elements and not the other way round. Is it currently possible to add pseudo-elements to SVG elements or is this not within spec? If not, are there any workarounds for achieving this effect?

like image 715
Ben Short Avatar asked May 04 '26 00:05

Ben Short


2 Answers

The :before and :after pseudo-elements do not work for elements inside a SVG tag. See MDN Reference

like image 99
Den Avatar answered May 05 '26 14:05

Den


No, it is not possible. The SVG specification does not support pseudo-elements (::before, ::after) on internal elements like <circle>, <rect>, or <path>.

Workarounds:

  1. Native Tooltip: Nest a <title> tag inside your circle. The browser will display a standard system tooltip.

    XML

    <circle cx="123" cy="152" r="2">
      <title>Newcastle</title>
    </circle>
    
    
  2. CSS (Sibling Selector): Place a hidden element (like <text> or <g>) immediately after the circle in the SVG code and show it on hover.

    CSS

    /* SVG: <circle id="newcastle" ... /> <text class="label">Newcastle</text> */
    
    .label { opacity: 0; pointer-events: none; transition: opacity 0.2s; }
    #newcastle:hover + .label { opacity: 1; }
    
    
  3. JavaScript: Listen for mouseenter/mouseleave on the circle to toggle a separate HTML overlay positioned on top of the map.

like image 27
Dog Avatar answered May 05 '26 13:05

Dog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!