Matt.
Matt.

Reputation: 11

What is the 'best practice' way of creating an icon button with an SVG?

I know of two ways to create an icon button using an SVG:

Method 1 - Import the SVG into the file and place it as a child of the button, using CSS to switch off the majority of the buttons styles (or restyle to however you need it to look).

Method 2 - Use the SVG in the buttons background-image CSS style, perhaps having the text of the button visually hidden to make the button accessible to assistive technology.

Aside from not being able to use CSS to apply some colour changes to the SVG in method 2, is there any pro's or con's of each approach? Is there a 'best practice' approach to consider?

Upvotes: 1

Views: 5005

Answers (1)

Method 3

Reference a SVG file
or icons in a spritesheet https://css-tricks.com/svg-sprites-use-better-icon-fonts/

<img src='icon.svg'>

Method 4

Inject SVG as DataURI - https://css-tricks.com/lodge/svg/09-svg-data-uris/

<img src="data:image/svg+xml;<svg viewBox='' ... </svg>">

Method 5

Use an Object (or Embed) tag

<object data="your.svg" type="image/svg+xml">
  <img src="yourfallback.jpg" />
</object>

Method 6

Use a Web Component to load a file and inject with Method #1

<load-file src="//load-file.github.io/heart.svg">

https://dev.to/dannyengelman/load-file-web-component-add-external-content-to-the-dom-1nd

Method 7

Use my (UNlicensed pet-project) https://iconmeister.github.io/ <svg-icon > Web Component (supported in all modern Browsers) that will include all SVG icon data in the source file.

For every icon you can choose if you want to create bare SVG Method 1
or inject the SVG as datauri into an IMG src Method 4.

So it is a single Component File download! No external SVGs or any libraries required.

Example code toolbar at: https://jsfiddle.net/WebComponents/5ct36swL/

All SVG can be styled, with attributes AND properties AND CSS/properties

(This does style Method 4 IMGs, because the whole IMG src is recreated (not on CSS changes!)

Upvotes: 5

Related Questions