5. Intermediate Topics: Grouping, Reusability, and Text
As your SVGs become more complex, you’ll need ways to organize your code, reuse common elements, and integrate text effectively. This chapter introduces crucial elements for these tasks: <g>, <defs>, <use>, and <text>/<tspan>.
5.1 Grouping Elements with <g>
The <g> element is used to group related SVG shapes together. This is incredibly useful for applying styles or transformations to multiple elements simultaneously. Any attributes applied to a <g> element are inherited by its child elements.
Benefits of Grouping:
- Organization: Makes your SVG code more readable and manageable.
- Styling: Apply
fill,stroke,opacity, etc., to the group, and all children will inherit them (unless overridden by a child’s specific attribute). - Transformations: Apply
translate,rotate,scale, etc., to the entire group.
Example:
<svg width="300" height="200" viewBox="0 0 300 200">
<!-- Group 1: A blue rectangle and circle -->
<g fill="skyblue" stroke="blue" stroke-width="2">
<rect x="10" y="10" width="80" height="80" />
<circle cx="50" cy="50" r="30" />
</g>
<!-- Group 2: A red square and triangle, moved and styled -->
<g transform="translate(150, 50)" fill="lightcoral" stroke="red" stroke-width="3">
<rect x="0" y="0" width="70" height="70" />
<polygon points="35,0 70,70 0,70" />
</g>
</svg>
Explanation: In the second group, transform="translate(150, 50)" moves both the rectangle and the polygon 150 units to the right and 50 units down from their original positions. Their fill and stroke are also inherited from the group.
5.2 Reusing Elements with <defs> and <use>
The <defs> and <use> elements are essential for creating reusable SVG components, similar to how symbols work in graphic design software.
<defs>: Stands for “definitions.” This element is used to store reusable SVG components that are not rendered directly. Think of it as a library for your SVG assets. Items inside<defs>are typically invisible until referenced by a<use>element.<symbol>: A special element that can be placed inside<defs>. It’s used to define graphic template objects. Unlike other elements in<defs>,<symbol>can have its ownviewBoxandpreserveAspectRatio, making it very powerful for icon systems and reusable graphics.<use>: This element references an existing SVG element (like a<rect>,<circle>,<path>, or<symbol>) defined elsewhere in the SVG document. It creates a “shadow DOM” copy of the referenced element.
Key Attributes for <use>:
href(orxlink:hreffor older SVG versions): Points to the ID of the element you want to reuse (e.g.,#myCircle).x,y: Offsets the position of the reused element.width,height: Resizes the reused element (particularly useful for<symbol>elements).
Example:
<svg width="300" height="200" viewBox="0 0 300 200">
<defs>
<!-- Define a reusable star shape -->
<polygon
id="star"
points="50,0 60,35 95,35 65,60 75,95 50,70 25,95 35,60 5,35 40,35"
fill="gold"
stroke="darkgoldenrod"
stroke-width="2"
/>
<!-- Define a symbol for an icon -->
<symbol id="gear-icon" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="gray" />
<path
d="M50 0 L60 20 L40 20 Z M0 50 L20 60 L20 40 Z M50 100 L40 80 L60 80 Z M100 50 L80 40 L80 60 Z"
fill="lightgray"
/>
<circle cx="50" cy="50" r="15" fill="black" />
</symbol>
</defs>
<!-- Use the defined star at different positions -->
<use href="#star" x="0" y="0" transform="scale(0.5)" />
<use href="#star" x="100" y="50" />
<use href="#star" x="200" y="0" transform="scale(0.8) rotate(45)" />
<!-- Use the defined gear icon -->
<use href="#gear-icon" x="10" y="100" width="50" height="50" />
<use
href="#gear-icon"
x="80"
y="100"
width="80"
height="80"
fill="silver"
stroke="black"
stroke-width="1"
/>
</svg>
Key Takeaways:
- Elements inside
<defs>are templated. They are not rendered until referenced by<use>. <symbol>is particularly useful for creating icon sets. ItsviewBoxensures that the symbol scales proportionally regardless of thewidth/heightset on<use>.- You can override some presentation attributes (like
fill,stroke) on the<use>element itself. Transformations (transform) also apply to the<use>element. - The
hrefattribute is now the standard for linking (thexlink:hrefprefix is deprecated in modern SVG/HTML5 contexts).
5.3 Working with Text: <text> and <tspan>
SVG provides elements to embed text directly into your graphics. This text remains vector-based and is searchable, selectable, and accessible.
<text>: Defines a block of text.<tspan>: A child element of<text>, used to define a subsegment of text with different styling or position. Similar to<span>in HTML.
Key Attributes for Text:
x,y: Coordinates of the baseline of the text’s starting point.font-family: Specifies the font.font-size: Specifies the size of the font.fill: The color of the text.text-anchor: Aligns text horizontally (start,middle,end).dominant-baseline/alignment-baseline: Aligns text vertically (auto,middle,central,baseline,hanging, etc.).dominant-baselineis generally preferred for cross-browser consistency.dx,dy: Relative offsets for individual text characters or<tspan>elements.
Example:
<svg width="400" height="200" viewBox="0 0 400 200">
<!-- Basic text -->
<text x="20" y="30" font-family="Arial" font-size="20" fill="navy">Hello SVG!</text>
<!-- Centered text with different fill -->
<text
x="200"
y="80"
font-family="Georgia"
font-size="30"
fill="darkgreen"
text-anchor="middle"
>
Centered Text
</text>
<!-- Text with multiple tspans -->
<text x="20" y="150" font-family="Verdana" font-size="24" fill="purple">
This is
<tspan fill="orange" font-weight="bold">bold</tspan>
and
<tspan fill="blue" font-style="italic">italic</tspan>
text.
</text>
<!-- Text with dx/dy for fine positioning -->
<text x="20" y="190" font-family="monospace" font-size="16">
S<tspan dx="5" dy="-5">u</tspan>p<tspan dx="5" dy="5">e</tspan>r
<tspan dx="5">T</tspan>e<tspan dx="5" dy="-5">x</tspan>t
</text>
</svg>
Accessibility for SVG Text:
Since SVG text is plain text, it’s inherently more accessible than text embedded in raster images. Screen readers can often read it directly. However, for context:
- Use
titleanddescelements inside the parent<svg>or<g>for complex graphics. - Ensure sufficient contrast for text colors.
- For decorative text, you might use
aria-hidden="true"on the<text>element if it repeats information already present.
Exercises/Mini-Challenges
Icon Library:
- Create a
<defs>section with at least three different simple icons (e.g., a simple arrow, a home icon, a settings gear). Define each as a<symbol>with its ownviewBox. - Then, use
<use>to display each icon multiple times on the SVG canvas, applying differentx,y,width,height,fill, andtransformattributes to the<use>elements.
- Create a
Company Logo Recreation:
- Choose a simple company logo (e.g., a stylized letter or a simple abstract shape).
- Recreate it using
<g>,<path>, and basic shapes. - Use
<defs>and<use>if there are repeating elements. - Add the company name next to the logo using
<text>, styling it withfont-family,font-size, andfill.
Basic Bar Chart Labels:
- Create a simple bar chart with 3-4 rectangles (as you learned in basic shapes).
- Above each bar, add text using
<text>to display its value. - Below each bar, add text for its label (e.g., “Jan”, “Feb”).
- Use
text-anchor="middle"and adjustx,ycoordinates to align the text correctly with the bars.
“Text on a Path” (Bonus - advanced text):
- Research the
<textPath>element. - Create a curved
<path>(e.g., using a quadratic Bézier curve). - Make some text follow that curved path. This is a powerful feature for unique typography in SVG!
- Research the