代码之家  ›  专栏  ›  技术社区  ›  Crashalot

SVG:如何在元素内部均匀地将多行文本居中?

  •  0
  • Crashalot  · 技术社区  · 7 年前

    This answer 和 this answer 解释如何显示多行文本以及如何使用SVG将一行文本居中,但如何将多行文本居中?

    你可以从中看到 this Code Pen ,文本块未居中,因为 dy 属性,该属性是显示多行所需的。

    目标是允许动态插入/删除行,同时保留文本块的居中性质。因此,用户可以添加第四行或删除两行。在这两种情况下,文本块应保持居中。

    一种方法是修改 dy

    <svg style="border:1px solid black" width="200" height="300">
        <text x="50%" y="50%" font-size="15">
            <tspan x="0" dy="1.2em" dominant-baseline="central">tspan line 1</tspan>
            <tspan x="0" dy="1.2em" dominant-baseline="central">tspan line 2</tspan>
            <tspan x="0" dy="1.2em" dominant-baseline="central">tspan line 3</tspan>
        </text>
    </svg>
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Community Mohan Dere    6 年前

    dy

    text{text-anchor:middle;dominant-baseline:central;}
    <svg style="border:1px solid black" width="200" height="300">
        <text x="50%" y="50%" font-size="15">
            <tspan x="100" y="150" dy="-1.2em" >tspan line 1</tspan>
            <tspan x="100" y="150" >tspan line 2</tspan>
            <tspan x="100" y="150" dy="1.2em" >tspan line 3</tspan>
        </text>
    </svg>

    使现代化

    OP评论说,他们:

    在这种情况下,我会将整个文本放在一个组中,并使用组的边界框将文本居中:

    我添加的红色圆圈只是为了看到SVG画布的中心。

    let bb = txt.getBBox(); console.log()
    let X = 100;
    let Y = 150 - bb.y - (bb.height)/2;
    txt.setAttributeNS(null,"transform",`translate(${X},${Y})`)
    text{text-anchor:middle;dominant-baseline:central;font-size:15;}
    <svg style="border:1px solid black" width="200" height="300">
     <text id="txt"><!--
    --><tspan x="0" y="0">tspan line 1</tspan><!--
    --><tspan x="0" y="1.2em">tspan line 2</tspan><!--
    --><tspan x="0" y="2.4em" >tspan line 3</tspan><!--
    --><tspan x="0" y="3.6em" >tspan line 4</tspan>
     </text>
    <circle cx="100" cy="150" r="3" fill="red"/>
    </svg>