📅  最后修改于: 2023-12-03 15:05:24.753000             🧑  作者: Mango
SVG (Scalable Vector Graphics) is an XML-based vector image format used for creating interactive and scalable graphics. One of its core features is the ability to manipulate text in various ways, including aligning it in the middle of an SVG element.
To center text in an SVG element, we can use the text-anchor
property along with the alignment-baseline
property. The text-anchor
property sets the alignment of the text relative to its position, while the alignment-baseline
property sets the reference baseline for the text.
<svg width="200" height="100">
<rect x="0" y="0" width="200" height="100" fill="#eee"/>
<text x="100" y="50" text-anchor="middle" alignment-baseline="middle">Centered Text</text>
</svg>
This code will create a 200x100 SVG element with a gray background (#eee
), and a centered text that says "Centered Text". The x
and y
attributes of the text
element determine its position within the SVG. The text-anchor
property is set to "middle", which centers the text horizontally, and the alignment-baseline
property is set to "middle", which centers it vertically.
Apart from centering text, we can also align it left, right, or justify it. For left alignment, we can set the text-anchor
property to "start". For right alignment, we can set it to "end". For justified text, we can set it to "justify".
<svg width="200" height="100">
<rect x="0" y="0" width="200" height="100" fill="#eee"/>
<text x="10" y="50" text-anchor="start" alignment-baseline="middle">Left Aligned Text</text>
<text x="190" y="50" text-anchor="end" alignment-baseline="middle">Right Aligned Text</text>
<text x="100" y="70" text-anchor="middle" alignment-baseline="middle">Justified Text</text>
</svg>
This code will create a similar SVG element as before, but with three lines of text aligned differently. The first line is left aligned, the second is right aligned, and the third is justified.
In conclusion, SVG provides powerful text manipulation capabilities, including alignment options such as centering, left aligning, right aligning, and justifying. By combining the text-anchor
and alignment-baseline
properties, we can achieve precise text alignment within an SVG element.