Making an SVG button stretching in width with CSS background

While I was coding Amore's website, I stumbled across a challenge. I have these buttons I designed in Illustrator + Sketch, which is basically an SVG with some text on top of it. These buttons should change their width according to the amount of text they have.

If this was a "normal" button, I'd set the display: inline-block and give it padding to the top, bottom and sides. Something like this:

.button {
   font-size: 16px;
   text-transform: uppercase;
   display: inline-block;
   padding: 16px 36px;
   border-radius: 8px;
   background-color: #FFFFFF;
   color: #00253D;
}

But because I'm dealing with an odd-looking button, I had to come up with a solution.

The first thing I thought was to have 3 different SVG’s, with small, medium and large width. Then I would use JavaScript to check the content of each button, and change its background according to that.

But the problem is I would loose the ability to dinamically stretch the button’s width. After a few minutes searching for an answer, I found this StackOverflow post. I see someone posted about this preserveAspectRatio SVG property, so I ended up reading about that at w3.org and discovered what I needed to do was to set that property to none.

So here's how it's done. Lets see what I was trying to achieve.

Button stretches in width

I wanted the width of the background to stretch only in width, to fit the text content.

The HTML is just an <a> tag with a class:

<a href="url.com" class="button">Hello World</a>

The CSS is also simple:

.button {
   display: inline-block;
   padding: 16px 36px;
   font-size: 16px;
   line-height: 16px;
   text-transform: uppercase;
   color: #00253D;
   background: url(./path-to-your-svg-image.svg) no-repeat
}

Then to make this all work, I'll open up my SVG on VSCode and add preserveAspectRatio="none" to the opening tag:

<svg viewBox="0 0 230 54" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg">

And it's done! This works both with scaling the background in width, but also in height.

The only limitation I see with this method is that we have no way of controlling the background’s color. That could be achieved by having the SVG in the HTML, inside the <a> tag, and then changing the color using CSS.

However, this background-image method works wonders for me, and in the case of having to have another button color, I just upload the same SVG, but with a different color.

Hope you find this useful, take care!