Use SVG element to group related shapes to simplify transforms and styling

Tuesday, November 3, 2020

When you have a relatively complex visualization you'll get to a point where you'll need to do a transform on shapes. If you have put a bit of work in up front to group these shapes applying transforms and styles becomes a lot easier.

Code Examples

Using SVG group element

<?xml version="1.0" encoding="UTF-8"?>
<svg width="500" height="500">
  <!-- styles will apply to all shapes in group -->
  <!-- transform will apply to all shapes in group -->
  <g fill="yellow" stroke="orange" stroke-width="2" transform="translate(0,0)">
    <circle cx="50" cy="50" r="10"></circle>
    <rect x="150" y="100" width="100" height="100"></rect>

Duplicated styles on related shapes

<?xml version="1.0" encoding="UTF-8"?>
<svg width="500" height="500">
  <!-- repeating styles on related shapes -->
  <circle fill="yellow" stroke="orange" stroke-width="2" cx="50" cy="50" r="10"></circle>
  <rect fill="yellow" stroke="orange" stroke-width="2" x="150" y="100" width="100" height="100"></rect>
Tom Eustace

Reformed Java developer specializing in frontend technologies, mostly Angular (Nx), Svelte, Vue and D3.

Discussions are healthy ❤️