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?
The :before and :after pseudo-elements do not work for elements inside a SVG tag. See MDN Reference
No, it is not possible. The SVG specification does not support pseudo-elements (::before, ::after) on internal elements like <circle>, <rect>, or <path>.
Workarounds:
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>
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; }
JavaScript: Listen for mouseenter/mouseleave on the circle to toggle a separate HTML overlay positioned on top of the map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With