【问题标题】:Centered text both vertical and horizontal inside a circle在圆圈内垂直和水平居中文本
【发布时间】:2018-07-19 18:58:00
【问题描述】:

我想在这个圆圈内垂直和水平居中文本(两行),但是出了点问题:

SVG wrong

SVG wrong preview

我还尝试在中心放置背景图像,但我希望它位于虚线/虚线边框图层下方,而不是上方。请问有什么建议吗?

文本应该是这样的,但我希望它是文本,而不是 tspan。当然还有一个居中的背景图片。

Good example

【问题讨论】:

    标签: svg


    【解决方案1】:

    如果您不想使用tspan,则需要两个text 元素。您可以将两个元素的坐标设置为 50%/50%,然后..

    • 要在该点上水平居中,请使用text-anchor middle
    • 要将第一行放在该点上方,第二行放在该点下方,请使用alignment-baseline baseline/hanging(要在行之间获得更多空间,您需要稍微调整y 坐标)。

    例子:

    <svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
        <style>
            text {
                font-family: sans-serif;
                font-size: 30px;
            }
        </style>
    
        <circle cx="50%" cy="50%" r="45%" stroke="tomato" stroke-width="8" stroke-dasharray="20" fill="none" />
        
        <!-- Anchors in action -->
        <text x="50%" y="50%" text-anchor="middle" alignment-baseline="baseline">First row</text>
        <text x="50%" y="50%" text-anchor="middle" alignment-baseline="hanging">Second row</text>
    </svg>

    编辑

    多于两行,使用一个text 元素和多个tspan 元素会更容易。同样,将 text 居中在 50%/50%,并使用 dy 属性字节均匀地分隔 tspans。 注意dy 与之前的tspan 的关系

    <svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
        <style>
            text {
                font-family: sans-serif;
                font-size: 30px;
            }
            tspan {
                alignment-baseline: central;
            }
        </style>
    
        <circle cx="50%" cy="50%" r="45%" stroke="tomato" stroke-width="8" stroke-dasharray="20" fill="none" />
    
        <text x="50%" y="50%" text-anchor="middle">
            <tspan x="50%" dy="-2em">First row</tspan>
            <tspan x="50%" dy="1em">Second row</tspan>
            <tspan x="50%" dy="1em">Third row</tspan>
            <tspan x="50%" dy="1em">Fourth row</tspan>
            <tspan x="50%" dy="1em">Fifth row</tspan>
        </text>
    </svg>

    【讨论】:

    • 谢谢,这些对齐成功了。它运作良好。非常感谢!
    • 还有一个问题:如果我有 5 行并且想让它们都垂直居中在另一行下方怎么办?
    • @DanielIlaş 我已经用多线解决方案更新了我的答案。相关问题:stackoverflow.com/questions/31469134/…
    猜你喜欢
    • 2015-03-15
    • 2021-11-18
    • 2015-09-25
    • 2013-08-08
    • 2012-03-14
    • 2017-06-28
    • 1970-01-01
    • 2016-07-01
    相关资源
    最近更新 更多