SVG in HTML5
SVG Styling with CSS
In this chapter, we are going to learn how to apply styles to SVG elements using CSS. Using CSS in SVG allows for greater control over the visual appearance of graphics and helps make the design more dynamic and easy to maintain. We will explore how to change colors, apply opacities, add borders, and work with gradients.
Introduction to CSS in SVG
Just like in HTML, SVG elements can be styled using CSS. We can apply styles directly in the SVG file with inline styles or define external styles in CSS style sheets. Using CSS to style SVG makes the design more flexible and consistent, especially if we have multiple graphics that share similar styles.
Basic Example of Inline Styles
html
In this case, the fill
, stroke
, and stroke-width
styles are applied directly to the <rect>
element. Although this is an effective way to style SVG, it can become complicated when working with more complex graphics.
Applying Styles with External CSS Stylesheets
Using an external CSS stylesheet for SVG allows for defining styles in one place and applying them to multiple SVG elements. Below is an example of how CSS styling would be applied to an SVG file:
html
css
In this example, CSS classes are added to SVG elements, and styles are applied from an external stylesheet, allowing for more organized code.
Controlling Colors with fill
and stroke
In SVG, colors are primarily applied through two properties: fill
and stroke
.
fill
: Defines the fill color of a shape.stroke
: Defines the border color of a shape.
Example of fill
and stroke
html
This example shows how the fill
and stroke
attributes allow customization of both the fill color and the border of an SVG shape.
Gradients in SVG
Gradients allow for smooth transitions between colors and can add visual depth to SVG graphics. There are two main types of gradients in SVG: linear and radial.
Linear Gradient
html
Radial Gradient
html
Gradients are defined in the <defs>
element and applied using fill="url(#gradient_id)"
.
Opacity and Transparency
Opacity in SVG can be controlled at the shape level or at the stroke and fill level. The opacity
property affects the total opacity of the element, while fill-opacity
and stroke-opacity
control the transparency of just the fill or border.
html
Conclusion
Applying styles in SVG using CSS opens up a world of possibilities for enhancing the visual appearance of graphics. With properties like fill
, stroke
, opacity
, and the use of gradients, we can make SVG graphics more attractive and customized. In the next chapter, we will learn about transformations in SVG, a key tool for precisely manipulating and positioning elements.
See you in the next chapter!