html - 将 SVG 高度和宽度设置为其内部 <text> 节点的高度和宽度

标签 html css svg height inline

有没有办法让 SVG 元素的宽度和高度等于 text 节点内文本的宽度?

这是一个演示:

http://codepen.io/Tiger0915/pen/LEyePy

这是 SVG 标记:

<span>I want </span>

<svg width="100%" height="80px">
  <text x="0" y="0" fill="white">
    THESE WORDS
  </text>
</svg>

<span>to be an SVG</span>

理想情况下,我希望将 SVG 视为内联元素(例如 span 节点)。

我希望它像这样呈现:

I want THESE WORDS to be an SVG

THESE WORDS 是一个 SVG。

如果我在 svg 节点上执行 width="auto"height="auto",它根本不会呈现。

如何使 SVG 元素自动适应其中文本元素的宽度?

最佳答案

我不知道有任何 SVG+CSS 解决方案。

您可以使用一些 JavaScript 来调整大小:

// get the bounding box for the text element
var bbox = text.getBBox();

// set the svg width/height accordingly
svg.setAttribute( 'width', bbox.width );
svg.setAttribute( 'height', bbox.height );

// set the viewbox accordingly
svg.setAttribute( 'viewBox', bbox.x + ' ' + bbox.y + ' ' + bbox.width + ' ' + bbox.height );

Modified Codepen

您的一般问题是,SVG 元素没有像其他图像那样的尺寸。你的 Canvas (理论上)是无限大小的。 因此,为了确定大小,浏览器必须使用所有包含的元素,渲染它们,获取渲染坐标并计算最大边界框。据我所知,没有浏览器会这样做。

关于html - 将 SVG 高度和宽度设置为其内部 <text> 节点的高度和宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28048785/

相关文章:

css - 增加 SVG 的宽度,保持高度不变。拉伸(stretch) SVG

html - flex 盒 : content rules the width?

html - 我应该注意什么 CSS/HTML 功能?

javascript - D3js SVG 重叠 : Custom Colors with Many SVGs of random shape

javascript - 我想使用 angularjs 刷新图像的 div 标签 onclick

javascript - 如何在 selenium 中使用 JavascriptExecutor 右键单击​​ svg 元素

javascript - 什么是好的 CSS/HTML/SVG/Javascript 来为分数 0 到 10 做一个循环图像? (需要在 IE 7 和其他常见浏览器上工作)

HTML5 Canvas 颜色区分

html - CSS - 如何并排显示两个不同的帖子?

html - 在 Google Chrome 中打印表格时,内容与标题重叠