SVG tips & tricks
By now, SVG might seem straightforward, but trust me, it has its quirks that can make your data visualization journey challenging.
In this lesson, I'll share some tips and tricks that can save you hours of frustration β lessons I learned the hard way.
No Background Color in SVG
SVG elements like <circle>, <rect>, and <g> don't support CSS properties like background-color or border β they get silently ignored.
To add a colored background behind your shapes, draw a rectangle that covers the desired area. For a border effect, use a rectangle with a stroke and fill="none".
Here's an example:
π‘ Using backgroundColor directly on the <svg> tag can work for inline SVG in modern browsers, but it's not part of the SVG spec and may break in other contexts. The <rect> approach is the reliable way.
Text Alignment in SVG
Forget text-align β it doesn't work in SVG. Instead, you control text positioning with two SVG-specific properties: text-anchor for horizontal alignment and alignment-baseline for vertical alignment.
Remember, in JSX, CSS properties should be camelCased (e.g., textAnchor instead of text-anchor).
Play with the dropdowns below to see how they work:
text-anchor controls the horizontal alignment βalignment-baseline controls the vertical alignment βOh no! π±
It seems like you haven't enrolled in the course yet!
Join many other students today and learn how to create bespoke, interactive graphs with d3.js and React!
Enrollment is currently closed. Join the waitlist to be notified when doors reopen:
Or Login