Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG Text-anchor top left

By default, the anchor for the text element in SVG is at the bottom left, but I want it to be at the top left, since I am also creating a rectangle to act as the background for the text, but it is displayed incorrectly since the text is higher than the rectangle (because rectangle anchor/offset is at the top left). Is there a way to fix this, so both text and rectangle can be drawn at same coordinates and be displayed in the same location.

like image 719
Dominic Edhouse Avatar asked Jul 27 '15 14:07

Dominic Edhouse


People also ask

How do I align text Center in SVG?

Set the position of the text to the absolute center of the element in which you want to center it: If it's the parent, you could just do x="50%" y ="50%" . If it's another element, x would be the x of that element + half its width (and similar for y but with the height).

What is Tspan tag?

Definition and Usage. The <span> tag is an inline container used to mark up a part of a text, or a part of a document. The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id attribute.

What is baseline alignment?

The alignment-baseline attribute specifies how an object is aligned with respect to its parent. This property specifies which baseline of this element is to be aligned with the corresponding baseline of the parent. For example, this allows alphabetic baselines in Roman text to stay aligned across font size changes.


2 Answers

The dominant-baseline property/attribute worked for me:

svg {
  dominant-baseline: hanging;
}
like image 121
Jacob Avatar answered Sep 20 '22 12:09

Jacob


The coordinates (x and y) you supply for text elements is used as the baseline of the text. This makes sense because if there is text with varying font sizes on the same line, you would want their baselines to line up.

There is no "automatic" way to do what you want. SVG elements are always absolutely positioned.

You will just have to move the text down a bit by making the y coordinate a bit larger.

Alternatively, you could add a dy attribute to shift the text down a bit. Or even use a transform attribute to do the same. But using either of those methods wouldn't really be simplifying the process for you.

like image 42
Paul LeBeau Avatar answered Sep 19 '22 12:09

Paul LeBeau