How to apply a style to an embedded SVG?
CSS can style an inline SVG similar to how it styles HTML. Take a look:
In the above script, a red fill is applied to the circle element directly within the SVG's inline code.
Inline SVG styling methods
Styling your SVGs can be approached in a multitude of ways, depending on your use-case and how the SVGs are utilized within your HTML. Now let's get our hands dirty with some code.
Method 1: Append style with JavaScript
With embedded SVGs via an <img>
or <object>
tag, external CSS styling may not be possible due to cross-document boundaries. Instead, inject styles or an external stylesheet using JavaScript after the SVG is fully loaded:
Method 2: Custom Elements and Shadow DOM
By using customElements.define()
, you can create a custom SVG element and protect its styles with Shadow DOM, Confused? Behold:
Method 3: External Libraries (SVGInject)
Sometimes, you need a helping hand. External libraries like SVGInject provide a smooth approach to inject and style SVGs, just like this:
Advanced SVG styling techniques
These methods would take your SVG styling game to the next level. Ready to wield the power of SVG styles?
Technique 1: SVG CSS via '@import' statement
Keep your SVG styles separate and organized using CSS's @import
rule inside an SVG's style tag:
Technique 2: Avoiding Attribute Overrides
Inline SVG attributes like fill
may override your CSS properties. Tip: Remove such attributes and let CSS take the steering wheel:
Technique 3: <object>
& <iframe>
SVG Handling
When using <object>
or <iframe>
for your SVGs, directly inject stylesheets or style blocks via accessing the contentDocument:
Was this article helpful?