There is a way to make
image.svg#2 point to a variant of the same image.
| || || || |
This is the same image 4 times. Only one svg is downloaded as the part after the
# is not sent in the
:target pseudo class
The trick is to use CSS. Thanks to the
:target selector we can differentiate between various states of the image.
The ` :target` pseudo-class represents the unique element, if any, with an id matching the fragment identifier of the URI of the document.
A fragment identifier of a URI is the part that comes after the
# in the URI. In other words: if the uri is
bucket.svg#fill1 the fragment is
:target will match the element with
id="fill1". By cleverly using this you can do some cool things.
How to use it in SVG
SVG allows you to add a style sheet. This can be placed in the
defs element of the code. The following SVG code resembles the code of
bucket.svg from above.
The image below explains the structure:
Each level of filling has its own element filling the bucket to the desired level. Because all the
fill... elements have
visibility: hidden, only the
fill... that is in the fragments specifier will be shown (because the visibility is overwritten).
Showing and hiding multiple elements
The fragment specifier can only match one element at a time. If you want to match multiple elements, you can assign them a
class, for example
hidden. By assigning an
id to the root
svg-tag itself, the CSS selector
:root:target .hidden will select all elements with the class
:root element is an identifier for the root
svg-tag. Note that if there is no
id assigned to the root element, the URI without fragment specifier will target the root element in some browsers.
The same trick can be used by grouping all elements in multiple
<g> tags, and assigning each of them with a unique id. the code below gives an example