× Search About Posts Code Music Links
Blank Try
experiment
lots
learn
more

SVG Coding

Updated on
Last site update: 8 May 2024

Calling a single from a sprite

1<svg class="icon icon-twitter-logo">
2  <use xlink:href="/path/to/images/my-sprite.svg#icon-twitter-logo"></use>
3</svg>

The xlink: bit is deprecated apparently.

CurrentColor

It’s common to use SVG icons inside links for menus etc.. But the CSS usually targets either the color or background-color. An SVG will usually want it’s fill property changed though, or sometimes the stroke. An easy way to this is to set the fill color to ``currentColor`. This property will take the colour being used at the time including the colour of the hover state.

SVG

The <svg> is the main container for one or more SVG’s.

<g> <symbol> <title>

Using SVG’s

There are 7 ways to add SVG’s to a web page:

  1. Using the <img> tag : can’t target with CSS so you can’t use :hover etc.

  2. Inline - paste the code straight into the page. Can modify colour using the fill attribute or with CSS IF the fill attribute is removed. You can add an id or class attributes to the <svg> tag OR to the <path>. Using the <path> allows to target different paths on images that use multiple paths.

  3. Using the SVG within the CSS file;

    1section {
    2   background-image: url(path/to/file.svg) left top no-repeat;
    3   background-size: 100px 100px; /* important to make the image fit within the container */
    4   width: 100px;
    5   height: 100px
    6   display: block;
    7}
    

    You can’t change the colour with this method.

  4. Using CSS masks.

    1div {
    2    width: 200px;
    3    aspect-ratio: 1 / 1;
    4    background-color: blue;
    5    mask-image: url(path/to/image.svg);
    6    mask-size: 200px 200px;
    7}
    

    The mask-image and mask-size properties still require additional webkit- prefix for webkit browsers.

  5. You can add SVG code directly into an image tag’s source attribute. You have to prefix it first with a data URI.

    1<img src='data:image/svg+xml;utf8,<svg id="swan" etc...' >
    

    Two issues: first there is a conflict of double quotes here. So you have to use single quotes for either the src attribute or within the SVG, <img src='...' >

    Secondly you cannot use the # symbol either, as in colours #4512a7;. You can use CSS colour names like cadetblue or hotpink etc..

    Alternatively you can covert your SVG code to base 64 using a free service like Base 64 Image

  6. Using the <object> tag