gpt4 book ai didi

css - 自动缩放 SVG 以适应子内容的宽度(例如文本)[无 JS]

转载 作者:行者123 更新时间:2023-12-05 01:35:18 25 4
gpt4 key购买 nike

我发现的一切都是相反的,例如“如何缩放文本以适应 SVG”。但我想达到相反的目的:

我的 HTML 中的 SVG:

<svg class="text" xmlns='http://www.w3.org/2000/svg' stroke='black' fill='none'>
<text>
<tspan>Some Text</tspan>
</text>
</svg>

CSS:

svg.text {
font-size: 2.5rem; // changes on different screen sizes
height: 0.8em;
width: auto; // This doesn't work... the width becomes something weird, always the same, no matter the contents of the text
}
svg.text text {
transform: translateY(0.8em); // needed this to make the text visible at all
}

我想要 <svg>增长以匹配 text 的宽度元素,就像一个普通的 DOM 元素被设置为 display: inline-block;position: absolute;float: left;

有什么想法吗?

编辑

感谢 comment of @enxaneta我想到了这个:

JavaScript:

/**
* Fit SVGs to their first text child's viewBox
*/
fitSvgTextElements() {
const elements = document.querySelectorAll('svg.text');
for( const el of elements ) {
const box = el.querySelector('text').getBBox();
el.setAttribute('viewBox', `${box.x} ${box.y} ${box.width} ${box.height}`);
}
}

这行得通。但是有什么办法可以用纯 CSS/SVG 属性来解决这个问题吗?

最佳答案

由于 SVG 格式中的基本设计决策,没有脚本就无法实现您想要实现的尺寸更改。 spec像这样描述相关概念:

All SVG content is drawn inside SVG viewports. Every SVG viewport defines a drawing region characterized by a size (width, height), and an origin...

The width, height and origin of SVG viewports is established by a negotiation process between the SVG document fragment generating the SVG viewport, and the parent of that fragment (whether real or implicit)...

这意味着视口(viewport)的尺寸取决于它们的外部上下文,但独立于它们的内部内容。

您尝试通过其内容来调整视口(viewport)元素的大小会颠倒逻辑顺序,并且只能在最初完成渲染后才能实现。那时,只有脚本可以更改呈现的 DOM。

如何执行该脚本化解决方案,您已经在您的问题中进行了演示,尽管我会以不同的方式编写它。虽然 CSS 规则 width: auto; height: 1em 应该 就足够了,一些较旧的浏览器对此有问题。我更愿意计算 width <svg>的风格元素明确。 (width 属性的特异性低于 CSS 样式表规则。)

fitSvgTextElements() {
const elements = document.querySelectorAll('svg.text');
for( const el of elements ) {
const box = el.querySelector('text').getBBox();
el.setAttribute('viewBox', `${box.x} ${box.y} ${box.width} ${box.height}`);
// the <svg> element is in HTML context,
// so you need dimensions in relation to the page viewport
const viewport = el.getBoundingClientRect();
// retain height, recompute width in relation
const width = viewport.height * box.width / box.height;
el.style.width = `${width}px`;
}
}

关于css - 自动缩放 SVG 以适应子内容的宽度(例如文本)[无 JS],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63057178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com