Embedding and styling SVG documents with CSS in Rails

20 Feb 2016

Update: I published a gem based on this technique, called inline_svg, which you can use in your Rails views to embed and style SVG documents.

Styling a SVG document with CSS for use on the web is most reliably achieved by adding classes to the document and embedding it inline in the HTML.

To embed and style SVG documents in Rails I use this simple helper:

def embedded_svg filename, options={}
   file = File.read(Rails.root.join('app', 'assets', 'images', filename))
   doc = Nokogiri::HTML::DocumentFragment.parse file
   svg = doc.at_css 'svg'
   if options[:class].present?
     svg['class'] = options[:class]

Place a SVG document (without any CSS class attributes) into the app/assets/images/ directory and embedded_svg helper from a view template (HAML example):

!!! 5 
     %title Embedded SVG Documents
     %h1 Embedded SVG Documents
       = embedded_svg "some-document.svg", class: 'some-class'

Add CSS styles to target the class added to the SVG. For example this might be applicable for coloring and sizing an SVG icon:

.some-class {
  display: block;
  margin: 0 auto;
  fill: #3498db;
  width: 5em;
  height: 5em;

The example code applies equally well to non-Rails Ruby web applications; simply modify the file or directory path to suit your needs.