SvgSprite
Create SVG sprites by embedding images into CSS using data URIs. The SVGs are optimized using svg_optimizer.
Installation
$ gem install svg_sprite
Usage
Let's assume there's a directory called images
with the following files:
$ tree images
images
├── doc-fill.svg
├── doc.svg
├── trash-fill.svg
└── trash.svg
0 directories, 4 files
The following command will export the SVG sprite and a CSS file with all dimensions.
$ svg_sprite generate --input images \
--css-path sprite/icons.css \
--sprite-path sprite/icons.svg \
--name icon
All SVGs will be combined into one simple file. You can then refer to the SVG by using a link.
<svg>
<use href="sprite/icons.svg#trash" role="presentation">
</svg>
If you want to restrict the SVG to the original dimensions, use the export CSS
file. Classes are defined using the --name
name (defaults to sprite
),
together with the file name. This is an example:
/*
This file was generated by https://rubygems.org/gems/svg_sprite with the
following command:
svg_sprite generate --input images --sprite-path sprite/icons.svg --css-path sprite/icons.css --optimize
*/
.icon--doc-fill {
width: 42px;
height: 52px;
}
.icon--doc {
width: 42px;
height: 52px;
}
.icon--trash-fill {
width: 48px;
height: 53px;
}
.icon--trash {
width: 48px;
height: 54px;
}
By default, SVGs will keep their stroke and fill colors. You can remove or use
currentColor
instead by using --stroke
and --fill
.
$ svg_sprite generate --input images \
--sprite-path sprite/icons.svg \
--css-path sprite/icons.css \
--stroke current-color \
--fill current-color
$ svg_sprite generate --input images \
--sprite-path sprite/icons.svg \
--css-path sprite/icons.css \
--stroke remove \
--fill remove
Finally, all SVGs will be optimized using
svg_optimizer. To disable it, use
--no-optimize
.
Programming API
To export both the CSS and SVG files:
require "svg_sprite"
SvgSprite.call(
input: "./images/icons",
name: "icon",
css_path: "./sprite/icons.css",
svg_path: "./sprite/icons.svg",
optimize: true,
stroke: "remove",
fill: remove
)
Development
After checking out the repo, run bin/setup
to install dependencies. Then, run
rake test
to run the tests. You can also run bin/console
for an interactive
prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install
. To
release a new version, update the version number in version.rb
, and then run
bundle exec rake release
, which will create a git tag for the version, push
git commits and tags, and push the .gem
file to
rubygems.org.
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/fnando/svg_sprite. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
License
The gem is available as open source under the terms of the MIT License.