📜  SVG<style> Element(1)

📅  最后修改于: 2023-12-03 15:20:24.354000             🧑  作者: Mango

SVG <style> Element

The SVG <style> element allows you to embed CSS styles directly into your SVG document. It is used to define styles for SVG elements, similar to how CSS is used to style HTML elements.

Usage

To use the <style> element, you need to place it within the <svg> root element of your SVG document. Here is an example of how to include the <style> element in SVG:

<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">
  <style>
    /* CSS styles go here */
  </style>
  <!-- SVG content goes here -->
</svg>

Inside the <style> element, you can write CSS rules that target specific SVG elements using their element name, class, or ID. You can also use other CSS selectors like attribute selectors and pseudo-classes.

Examples

Here are a few examples of how you can use the <style> element in SVG:

  1. Applying a fill color to a <circle> element using its class:
.circle {
  fill: red;
}
<circle class="circle" cx="50" cy="50" r="40" />
  1. Applying a stroke color and width to a <rect> element using its ID:
#myRect {
  stroke: blue;
  stroke-width: 2;
}
<rect id="myRect" x="10" y="10" width="100" height="50" />
  1. Applying a transform to a <g> element:
.group {
  transform: translate(50, 50) rotate(45deg);
}
<g class="group">
  <!-- SVG content goes here -->
</g>
Supported CSS Properties

The <style> element supports a wide range of CSS properties that can be applied to SVG elements, including:

  • Fill and stroke properties (e.g., fill, stroke, stroke-width)
  • Typography properties (e.g., font-family, font-size, text-anchor)
  • Transformations (e.g., translate, rotate, scale)
  • Animation properties (e.g., animation-name, animation-duration)
  • And many more...

For a complete list of supported properties and their descriptions, you can refer to the SVG specification.

Limitations

There are a few limitations to keep in mind when using the <style> element in SVG:

  1. SVG does not support all CSS selectors and properties. Some CSS features may behave differently or not work at all in SVG.
  2. Inline styles defined directly on SVG elements take precedence over styles defined in the <style> element.
  3. External CSS stylesheets cannot be referenced directly in SVG and must be embedded within the <style> element.
Conclusion

The <style> element in SVG allows you to apply CSS styles to SVG elements, giving you control over their appearance and behavior. It offers a flexible and powerful way to create visually appealing and interactive SVG graphics.

For more information and examples, please refer to the MDN Web Docs on SVG <style>.