Skip to main content
Hero Background Image

Using Scalable Vector Graphics as Button Backgrounds

February 8, 2013

Last night I was working on a project where the mockups called for some assymetrical button shapes that were all different sizes. Rather than creating a half a dozen background images for each button length, I wondered if I might just use an SVG or Scalable Vector Graphic file as the background which I could then stretch as needed. As you know, there's no penalty of pixelation when stretching SVGs because they are not based on pixels. This would also save a lot of load time on the site, as I can load one vector image instead of half a dozen pixel-based images. 

I created the SVG in Illustrator by creating the shape then simply saving it as an SVG format. Then in the CSS, I referenced that file as the background image for my button. Here's where it got tricky. By nature, SVGs want to preserve their aspect ratio, which is noble. But I specifically wanted to stretch them horizontally only, while maintaining the same height. I tried many variations on background-size, height, width, etc. but I finally found the magic bullet on which said, "try removing the width and height attributes on the svg root element, adding preserveAspectRatio="none" viewBox="0 0 1024 800".

Brilliant! So I opened up the SVG file in Sublime Text 2 (any code editor will do, and I straight up hacked it. I simplified the xmlns attribute, removed a lot of the wrapper stuff that Illustrator threw in, and added in the value to tell the SVG to ignore the aspect ratio. The resulting file looks like this: 

Button.svg file (also attached as a zip file):

<svg xmlns="" viewBox="0 0 81.985 39.412" enable-background="new 0 0 81.985 39.412" xml:space="preserve" preserveAspectRatio="none">
<path fill-rule="evenodd" clip-rule="evenodd" fill="#5F6062"

I then wrote up a SASS mixin with some other necessary styles to make it easy to pop in a fancy button whenever I need one. 

SASS mixin:

@mixin button
  background-color: transparent
  background-image: url(../images/button.svg)
  background-size: 100% 100%
  border: 0
  padding: 8px 15px
  color: white

Then in my global.sass file, this is all I need to include:

.svg input.form-submit

Remember that older versions of IE do not support SVG. You can use Modernizr to add the .svg class to the <html> element, and then you can load the SVG image only when that body class is present. 

If you are already loading conditional stylesheets for IE, you can include a different button style there that uses a regular .png image background, a simple background color, or maybe a JS solution that gives IE a hand in rendering SVGs. There are a list of options to choose from depending on what best suites your needs. 

Related Insights