在IE11上使用text-anchor: middle和alignment-baseline: middle/central将SVG文本居中

5
我需要在IE11中完美地将文本元素居中在SVG中。
期望的结果(所有常青浏览器): enter image description here IE11的结果: enter image description here // SVG代码:
<svg xmlns="http://www.w3.org/2000/svg" width=100% height="100%" viewBox="0 0 130 130">
    <circle fill="dodgerblue" cx="50%" cy="50%" r="65"></circle>
    <text text-anchor="middle"
        alignment-baseline="central"
        font-size="75"
        font-family="Arial"
        x="50%" y="50%">1</text>
  </svg>

Codepen

2个回答

14

IE不支持alignment-baseline。实现您想要的最佳跨浏览器方式是使用具有分数em值的dy属性。

对于Arial,约dy="0.35"的值有效。

<svg xmlns="http://www.w3.org/2000/svg" width=100% height="100%" viewBox="0 0 130 130">
  <circle fill="dodgerblue" cx="50%" cy="50%" r="65"></circle>
  <text text-anchor="middle"
        font-size="75"
        font-family="Arial"
        x="50%" y="50%" dy="0.35em">1</text>
</svg>


也许这是一个愚蠢的问题……但是,你能详细说明为什么是0.35em而不是0.5em吗?我的意思是,如果1em = 字体高度,将其偏移0.5em应该就可以了(但实际上不行)… - digEmAll
这是因为字符字形的垂直中心通常不对应于 em 高度的垂直中心。例如,为下降部分保留的空间往往会将字形向上推在 em 方框中。可以参考微软网站上的此图表。 - Paul LeBeau
根据您的需求,您可能需要调整该值。但一旦您找到适合字体的' em '量,它就可以适用于该字体的任何大小。 - Paul LeBeau

0

我也同意@Paul LeBeau的观点。此外,我使用了这个工具https://petercollingridge.appspot.com/svg-editor来去除空白。以下方法对我很有效:

<svg viewBox="0 0 130 130" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg"><circle fill="dodgerblue" cx="50%" cy="50%" r="65"/><text font-family="Arial" font-size="75" text-anchor="middle" x="50%" y="50%" dy="0.36em">1</text></svg>

我可以使用JavaScript处理删除空格的任务:

let svg = `
    <svg viewBox="0 0 130 130" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
        <circle fill="dodgerblue" cx="50%" cy="50%" r="65"/>
        <text font-family="Arial" font-size="75" text-anchor="middle" x="50%" y="50%" dy="0.36em">1</text>
    </svg>
`;

// Note: Hack for IE11
// Optimize HTML by removing whitespace
// Ref: https://jaketrent.com/post/remove-whitespace-html-javascript/
svg = svg.replace(/\n/g, '') // remove newline/carriage return
    .replace(/[\t ]+\</g, '<') // remove whitespace (space and tabs) before tags
    .replace(/\>[\t ]+\</g, '><') // remove whitespace between tags
    .replace(/\>[\t ]+$/g, '>'); // remove whitespace after tags

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接