Last Updated: August 05, 2017
·
18.37K
· jamesmartin

Embedding and Styling Inline SVG Documents With CSS in Rails

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]
   end
   doc.to_html.html_safe
 end

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 
 %html
   %head
     %title Embedded SVG Documents
   %body
     %h1 Embedded SVG Documents
     %div
       = 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.

5 Responses
Add your response

this is a great helper method if you happen to already be using Nokogiri.

over 1 year ago ·

Thanks for this, worked perfectly!

over 1 year ago ·

@ch4s3: I made this code into the inline_svg gem, which declares its dependencies (Nokogiri) and adds itself as a Rails view helper.

over 1 year ago ·

@jamesmartin Brilliant! I saved this page a couple of weeks ago and was about to ask for that.

over 1 year ago ·

Awesome solution. Cheers!

over 1 year ago ·