SVG Icon Transformation for Bootstrap
When integrating SVG icons with Bootstrap, special processing is required to ensure proper color inheritance from Bootstrap's styling system. While SVGs can be used directly as image files via URL paths, this approach limits their flexibility since colors must be hardcoded in the SVG files themselves.
To achieve the same behavior as Bootstrap's native icons (where icons inherit colors from their parent elements),
SVGs need to be transformed into a specific format. This transformation can be achieved using the svgo (SVG Optimizer) tool.
Installation
Install SVGO globally using npm:
npm install -g svgo
Configuration
Create a configuration file (e.g., svgo.config.js) with the following settings to properly transform SVGs for Bootstrap compatibility:
module.exports = {
multipass: true,
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false,
cleanupIDs: false,
collapseGroups: false,
mergePaths: false,
convertShapeToPath: false,
convertPathData: false
}
}
},
'removeDimensions',
'convertStyleToAttrs',
'removeDoctype',
'removeComments',
'removeMetadata',
'removeTitle',
'removeDesc',
'sortAttrs',
{
name: 'convertColors',
params: {
currentColor: true
}
},
'collapseGroups',
{
name: 'addAttributesToSVGElement',
params: {
attributes: [{ fill: 'currentColor' }]
}
}
]
};
Transformation Process
The transformation process modifies SVG files to:
- Remove unnecessary metadata and attributes
- Convert colors to use
currentColorfor dynamic color inheritance - Preserve essential SVG structure while optimizing file size
- Enable proper color inheritance from Bootstrap's CSS system
Use this command to process all icons located in input path icons and output will be generated in icons_opt
svgo --config=svgo.config.js -f icons icons_opt
Integration with Bootstrap Studio
After transformation:
- Open Bootstrap Studio
- Add the processed SVG as a
Custom Codeelement - The icon will now inherit colors from its parent elements, just like native Bootstrap icons
This approach ensures your custom SVG icons behave consistently with Bootstrap's native icon system while maintaining full color customization capabilities through CSS.
<!-- Element where custom code is placed -->
<div style="color: var(--bs-primary);">
<!-- Custom code content -->
<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 149 149">
<path fill="none" stroke="currentColor" stroke-width="2.29" d="M106.557,15.579l-8.246,34.725l8.246,-34.725Z"></path>
</svg>
</div>
See also: Theme | User Controls