How to make svg text like inline-block

2019-09-17 04:29发布

Trying to create chart legend.

<svg>
    <g class="legend">
        <g>
            <rect fill="blue" width="1em" height="1em" />
            <text>Bosnia and Herzegovina</text>
        </g>
        <g>
            <rect fill="red" width="1em" height="1em" />
            <text>Democratic Republic of the Congo</text>
        </g>
    </g>
</svg>

Obviously, each item starts at (0, 0) on top of previous one. Is there a way to make them behave more like inline-block elements?

jsfiddle

标签: html css svg
1条回答
手持菜刀,她持情操
2楼-- · 2019-09-17 04:37

Not with 'pure' SVG. SVG doesn't have automatic text layout features like HTML. It expects you to position each piece of text yourself.

However, if you want to have a paragraph of text, and as long as your SVG is only going to be used in a browser, you can embed HTML inside your SVG using the <foreignObject> element.

https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject

查看更多
登录 后发表回答