gpt4 book ai didi

html - 如何使 SVG 中的文本居中?

转载 作者:太空狗 更新时间:2023-10-29 15:04:51 27 4
gpt4 key购买 nike

我需要在 SVG 对象的标记内将文本水平居中,而无需定义 x 坐标。我正在尝试寻找 text-align: CSS 居中的替代方法。我已经使用过 text-anchor: middle 但它不起作用。我有这个代码

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0" stop-color="#FFE89C" stop-opacity="1"/>
<stop offset="0.2" stop-color="#FFE192" stop-opacity="1"/>
<stop offset="0.4" stop-color="#ffd47a" stop-opacity="1"/>
<stop offset="0.6" stop-color="#ffc967" stop-opacity="1"/>
<stop offset="0.8" stop-color="#febd52" stop-opacity="1"/>
<stop offset="1" stop-color="#fdba4c" stop-opacity="1"/>
</linearGradient>
</defs>
<text fill="url(#grad1)" x="73" y="50">50</text>
</svg>

最佳答案

The text is centered relatively x-axis, and I want that it' center relatively parent SVG container, otherwise it turn out that if the length of text content changes, it will be necessary to change the x coordinate.

您只需将文本定位在 viewBox 中间的位置。然后,如果您使用 text-anchor="middle",文本将保持居中。

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 150 60">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0" stop-color="#FFE89C" stop-opacity="1"/>
<stop offset="0.2" stop-color="#FFE192" stop-opacity="1"/>
<stop offset="0.4" stop-color="#ffd47a" stop-opacity="1"/>
<stop offset="0.6" stop-color="#ffc967" stop-opacity="1"/>
<stop offset="0.8" stop-color="#febd52" stop-opacity="1"/>
<stop offset="1" stop-color="#fdba4c" stop-opacity="1"/>
</linearGradient>
</defs>

<text fill="url(#grad1)" x="75" y="50" text-anchor="middle"font-size="40">50</text>
</svg>

关于html - 如何使 SVG 中的文本居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31223852/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com