Style Element in SVG: Function and Usage
The <style> element placed directly inside an
Scalable Vector Graphics (SVG) document allows developers to embed
Cascading Style Sheets (CSS) rules within the graphic file itself. This
article explains the primary functions of the internal SVG
<style> tag, how it impacts presentation and
maintainability, its support for responsive design and animations, and
how it handles encapsulation across different embedding methods.
Internal CSS Rule Definition
The primary function of the <style> element in an
SVG is to define presentation rules for the graphic’s components using
standard CSS syntax. Instead of relying exclusively on presentation
attributes (such as fill="red" or
stroke="black" directly on <path>,
<circle>, or <rect> tags), you can
use class, ID, element, and pseudo-class selectors.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<style>
<![CDATA[
.shape {
fill: #007acc;
stroke: #003366;
stroke-width: 2;
transition: fill 0.3s ease;
}
.shape:hover {
fill: #ff6600;
}
]]>
</style>
<circle class="shape" cx="50" cy="50" r="40" />
</svg>Self-Contained Portability
Placing a <style> block directly inside an SVG
ensures the file is completely self-contained. When an SVG is
distributed, shared, or rendered as a standalone image file, all visual
formatting, fonts, and states remain intact without needing a link to an
external stylesheet.
Support for Media Queries and Animations
The internal <style> element supports advanced CSS
features:
- Media Queries (
@media): SVGs can alter their internal layout or color palette based on viewport dimensions. When the SVG is resized, media queries inside the<style>tag evaluate against the SVG’s own viewport (viewBox), enabling component-level responsive vector graphics. - Keyframe Animations (
@keyframes): You can define CSS animations directly inside the SVG, allowing paths and shapes to pulse, rotate, or morph without relying on SMIL (Synchronized Multimedia Integration Language) or external JavaScript.
XML Parsing and CDATA Sections
Because SVG is an XML-based format, certain CSS characters—such as
>, <, and &—can cause
XML parsing errors. Wrapping the stylesheet content in a
<![CDATA[ ... ]]> block inside the
<style> tag ensures that the XML parser treats the
CSS rules as raw character data rather than markup, preventing rendering
failures.
Scoping Behavior
The impact of the <style> element depends on how
the SVG is delivered:
- Loaded via
<img>,background-image, or<object>: The styles inside the<style>block are strictly encapsulated within the SVG’s isolated browsing context and cannot affect the surrounding web page. - Inlined directly into HTML: The
<style>element becomes part of the main document’s DOM. Unless selectors are uniquely named or scoped with specific classes, the CSS rules inside the SVG can bleed into and affect other HTML elements on the page.