Home > Mobile >  Add my own icon to <i> in HTML similar to Bootstrap's icons?
Add my own icon to <i> in HTML similar to Bootstrap's icons?

Time:08-13

Bootstrap has a nifty way of adding an icon:

<i ></i>

It's really nice cause I can add in the fs-1 class to control the sizing of the icon automatically.

I have my own icon in an SVG file, and would like to do the same:

<i ></i>

But I cannot figure out how to add my svg file to the element in css. I looked at the bootstrap code and they just had this:

.bi-arrow-right-square-fill::before { content: "\f136"; }

Can someone explain an example on how to load an svg file into a <i> HTML tag?

CodePudding user response:

Bootstrap is doing this via an icon font; the glyph in that font at codepoint \f136 in that font will be the icon instead of a normal letter glyph.

Creating or modifying icon fonts can be a bit fiddly; there are some web-based tools to make it a little simpler than working in a font editor, but in the long run I wouldn't recommend it. (They're a pain to maintain, since you have to regenerate and version the font every time you make a change, and cause significant problems for accessibility.)

Instead you could convert your SVG into a data:image URI and put that in your CSS, using whatever method is most convenient for your specific layout, for example

.foo::before {
    content: url('data:image/svg xml;utf8,<svg ... </svg>')
}

or

.foo {
  background: url('data:image/svg xml;utf8,<svg ... </svg>');
  width: ..., height: ...
}

...or, of course, just host the SVG at a real URI and embed it using CSS as you would any other image.

  • Related