internetoscar
internetoscar

Reputation: 83

How to insert an SVG into a button?

I am new to HTML and stuff and I would like to insert a SVG into a button. I tried using <object> but the SVG is invisible. Any suggestions what I could do to make it visible and fit inside the box?

Upvotes: 8

Views: 23846

Answers (1)

Harry Cutts
Harry Cutts

Reputation: 1424

There are a few different approaches. Possibly the easiest way to include an SVG is using an <img> tag, like you would for any other image type:

<button>
  <img src="https://api.iconify.design/ic-baseline-face.svg?height=24" aria-hidden="true">
  Smile
</button>

In this case, the size of the SVG we're importing is about right, but if it wasn't it might be more difficult to size it how you like, because you have two elements rather than one to think about. In that case, a good alternative is to set it as a background in CSS instead:

.my-button {
  width: 3em;
  height: 3em;
  background: url("https://api.iconify.design/ic-baseline-face.svg?height=24") center no-repeat;
}
<button class="my-button" aria-label="Smile"></button>

This approach is often used for icons, but note that in this method we have to specify a size (in this case using width and height in the CSS).

As a third option, you can include SVG source directly in HTML instead, which allows you to style it with CSS and manipulate it with JavaScript, but that's generally not very useful for button icons. For completeness, though you'd do it like this:

<button>
  <!-- From https://material.io/tools/icons/?style=baseline -->
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
    <path d="M9 11.75c-.69 0-1.25.56-1.25 1.25s.56 1.25 1.25 1.25 1.25-.56 1.25-1.25-.56-1.25-1.25-1.25zm6 0c-.69 0-1.25.56-1.25 1.25s.56 1.25 1.25 1.25 1.25-.56 1.25-1.25-.56-1.25-1.25-1.25zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8 0-.29.02-.58.05-.86 2.36-1.05 4.23-2.98 5.21-5.37C11.07 8.33 14.05 10 17.42 10c.78 0 1.53-.09 2.25-.26.21.71.33 1.47.33 2.26 0 4.41-3.59 8-8 8z"/>
    <path fill="none" d="M0 0h24v24H0z"/>
</svg>
</button>

CSS-Tricks has a good article on all three methods.

Upvotes: 12

Related Questions