Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between svg's x and dx attribute?

Tags:

svg

d3.js

People also ask

What is dx and dy in SVG?

x and y are absolute coordinates and dx and dy are relative coordinates (relative to the specified x and y ).

What is dx in css?

The dx attribute indicates a shift along the x-axis on the position of an element or its content.


x and y are absolute coordinates and dx and dy are relative coordinates (relative to the specified x and y).

In my experience, it is not common to use dx and dy on <text> elements (although it might be useful for coding convenience if you, for example, have some code for positioning text and then separate code for adjusting it).

dx and dy are mostly useful when using <tspan> elements nested inside a <text> element to establish fancier multi-line text layouts.

For more details you can check out the Text section of the SVG spec.


To add to Scott's answer, dy used with em (font size units) is very useful for vertically aligning text relative to the absolute y coordinate. This is covered in the MDN dy text element example.

Using dy=0.35em can help vertically centre text regardless of font size. It also helps if you want to rotate the centre of your text around a point described by your absolute coordinates.

<style>
text { fill: black; text-anchor: middle; }
line { stroke-width: 1; stroke: lightgray; }
</style>


<script>
dataset = d3.range(50,500,50);

svg = d3.select("body").append("svg");
svg.attr('width',500).attr('height', 500);

svg.append("line").attr('x1', 0).attr('x2', 500).attr('y1', 100).attr('y2', 100);
svg.append("line").attr('x1', 0).attr('x2', 500).attr('y1', 200).attr('y2', 200);

group = svg.selectAll("g")
    .data(dataset)
    .enter()
    .append("g");

// Without the dy=0.35em offset
group.append("text")
    .text("My text")
    .attr("x",function (d) {return d;})
    .attr("y",100)
    .attr("transform", function(d, i) {return "rotate("+45*i+","+d+",100)";});

// With the dy=0.35em offset
group.append("text")
    .text("My text")
    .attr("x",function (d) {return d;})
    .attr("y",200)
    .attr("dy","0.35em")
    .attr("transform", function(d, i) {return "rotate("+45*i+","+d+",200)";});
<script>

View it in Codepen

If you don't include "dy=0.35em", the words rotate around the bottom of the text and after 180 align below where they were before rotation. Including "dy=0.35em" rotates them around the centre of the text.

Note that dy can't be set using CSS.