svg中的文本居中不能正常工作



我在svg中矩形内的文本居中时有问题。我遵循了使用主导基线的建议,但是文本出现了几个像素,我想了解这是从哪里来的。

下面是两个并列标签的反应片段,一个使用svg,另一个使用flexx模型作为参考。

我们看到的差异的原因是什么?我如何实现相同的行为flexxalign项目和证明内容在svg?

const TestSvg = () => {
const x = 10;
const width = 52.35581970214844 ;
const y = 0;
const height = 14;
const svg = (
<svg width={'65px'} height={'30px'}>
<g width={width} height={height}>
<rect x={x} y={y} width={width} height={height} rx={'3px'} fill={'red'}/>
<text
x={x + width / 2} y={ y + height / 2}
style={{
fontSize: '11px',
fontWeight: 700,
fill: '#fff',
textAnchor: 'middle',
dominantBaseline: 'middle'
}}>{'BLA'}</text>
</g>
</svg>
)
const flex = (
<div>
<div style={{display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: 'red', borderRadius: '3px', width: width}}>
<div style={{
fontSize: '11px',
fontWeight: 700,
color: '#fff',
textAnchor: 'middle',
dominantBaseline: 'middle'
}}>{'BLA'}</div>
</div>
</div>
)
return (
<div style={{display: 'flex'}}>
{svg}
{flex}
</div>
)
}

我无法解释你报告的差异。

我做了一个香草版本的代码,并删除了<g><text>需要放在中间(50% 50%)。在SVG中,位置、大小等都是相对的。

:root {
--width: 100%;
--height: 100%;
}
svg>rect {
width: var(--width);
height: var(--height);
rx: 3px;
fill: red;
}
div#s1 {
display: flex;
align-items: center;
justify-content: center;
background-color: red;
border-radius: 3px;
width: 65px;
}
svg>text,
div#s1>div {
font-size: 11px;
font-weight: 700;
fill: #fff;
color: #fff;
text-anchor: middle;
dominant-baseline: middle;
}
<div style="display: flex;">
<svg width="65px" height="30px">
<rect x="0" y="0" />
<text x="50%" y="50%">BLA</text>
</svg>
<div id="s1">
<div>BLA</div>
</div>
</div>

最新更新