html - SVG 元素似乎具有任意高度

标签 html svg

我一直在努力学习一些 SVG。但是浏览器似乎陷入了一种正确的旧困惑状态。

采用以下 HTML:

<html>
  <head></head>
  <body>
    <svg xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink">
      <rect height="100" width="100" style="stroke:#006600; fill: #00cc00"/>
    </svg>
    <p>Hello? Hellooooooooooooo?</p>
  </body>
</html>

在任何现代浏览器中查看,您会在矩形和随后的 HTML 段落之间看到任意数量的空白。 (IE9 不显示任何内容,但没有人会对此感到惊讶。)

Firefox (Firebug) 不提供 svgrect 元素的高度。它只是软弱无力并说“自动”。

Opera 表示 svg 的高度为 150px,并且表示 rect 为“auto”。

Chrome 会站起来并给出两者的高度。 rect 为 102px(显然包括笔划),svg 为 428px。

我的期望是 svg 元素将是一个“瘦”容器(即不向其内容的尺寸添加任何内容),因此高度为 102 像素。

有谁知道正确的行为应该是什么以及我该如何解决这个问题?

最佳答案

您还没有明确定义 SVG 的宽度或高度,或者矩形的放置位置,甚至是 SVG 的哪一部分是感兴趣的。浏览器以不同的方式处理事情也就不足为奇了。

尝试定义宽度和高度:

<svg xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" width="102px" height="102px">
  <rect height="100" width="100" style="stroke:#006600; fill: #00cc00"/>
</svg>

或者,定义一个viewBox:

<svg xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" viewBox="0 0 102 102">
  <rect height="100" width="100" style="stroke:#006600; fill: #00cc00"/>
</svg>

或两者兼而有之:

<svg xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" viewBox="-50 -50 52 52" width="102px" height="102px">
  <rect height="100" width="100" style="stroke:#006600; fill: #00cc00"/>
</svg>

Here are some examples in action .

关于html - SVG 元素似乎具有任意高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8696270/

相关文章:

javascript - JQUERY 在检查元素是否有多个 'td' 父元素后获取该元素

javascript - DTM 中基于事件的规则的 'Conditions' 部分中的自定义脚本

javascript - 使用 Javascript 函数创建 SVG 元素

javascript - 如何将 json 对象放入测试文件 ("file.json"),然后在 d3.json ("file.json", function(error, root)) 中读取该文件?

html - float 在正常内容之后出现的元素

javascript - 如何使整个 <div> 可选择?

html - 包含其他 div 的 div 上的 svg 剪辑路径(无 css :clip-path)

css - SVG 填充颜色悬停过渡不动画

html - 无需使用 javascript 将 svg 元素包裹在圆圈中

javascript - 在子站点/子文件夹中找不到 SVG href ID