htmlcsssvgbuttonicons

How do I display a Bootstrap 4 SVG icon in a button with a CSS class?


I am using Bootstrap 4's SVG icons in my buttons. I have the code working with the SVG hardcoded into the page's HTML. Now I want to refactor the SVG into a CSS class. I have followed the Bootstrap 4 instructions for creating the CSS class but I cannot work out how to display the icon on my button. I've tried a lot of variations without success.

CSS:

.bi::before {
    display: inline-block;
    content: "";
    background-image: url('data:image/svg+xml,<svg width="2em" height="2em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"><path fill-rule="evenodd" d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"></svg>');
    background-repeat: no-repeat;
    background-size: 1rem 1rem;
}

HTML:

<a href="#" class="btn bi" role="button" download></a>

Your help is greatly appreciated.


Solution

  • Well, to make your code work, there is a couple of note you should consider it.

    According to the above notes, your final code should be something like this:

    .bi::before {
      content: "";
      display: inline-block;
      background-image: url('data:image/svg+xml,%3Csvg%20preserveAspectRatio%3D%22none%22%20viewBox%3D%220%200%2016%2016%22%20fill%3D%22currentColor%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20d%3D%22M.5%209.9a.5.5%200%200%201%20.5.5v2.5a1%201%200%200%200%201%201h12a1%201%200%200%200%201-1v-2.5a.5.5%200%200%201%201%200v2.5a2%202%200%200%201-2%202H2a2%202%200%200%201-2-2v-2.5a.5.5%200%200%201%20.5-.5z%22%20%2F%3E%3Cpath%20fill-rule%3D%22evenodd%22%20d%3D%22M7.646%2011.854a.5.5%200%200%200%20.708%200l3-3a.5.5%200%200%200-.708-.708L8.5%2010.293V1.5a.5.5%200%200%200-1%200v8.793L5.354%208.146a.5.5%200%201%200-.708.708l3%203z%22%20%2F%3E%3C%2Fsvg%3E');
      background-repeat: no-repeat;
      width: 2rem;
      height: 2rem;
    }
    <a href="#" class="btn bi" role="button" download></a>

    NOTE: You can also create an SVG file in your project and then directly refer to it in your background image property like regular images for easier usage.