d1vplg
Last Updated: August 05, 2017
·
11.66K
· jamesmartin
Me coding in regents park

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.

Say Thanks
Respond

5 Responses
Add your response

14544
377660a6dbb08dce3f1b6dc295a260f4

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

over 1 year ago ·
16722
9574ea0aded5ed4514d43a1365bc023d

Thanks for this, worked perfectly!

over 1 year ago ·
17647
Me coding in regents park

@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 ·
17681
A6cebe2f043dd41948e77f8eca1bb0e1

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

over 1 year ago ·
18140
F335cb3766142d9a7dda79b434aa9bed

Awesome solution. Cheers!

over 1 year ago ·