首页 > 解决方案 > 如何为嵌入在嵌入式 SVG 元素中的 HTML 正确设置高度

问题描述

目标是使嵌入在 SVG 元素中的 HTML 占据根 SVG 元素的全部宽度和高度,根 SVG 元素本身嵌入在 HTML 文档中。

但是,正如您从 Codepen 中看到的那样,width 属性似乎有效,但 height 属性无法影响根 SVG 元素。结果,嵌入的 div 不是 2688 像素高。

最终,SVG 根元素及其内容应该是 1242x2688。

怎么了?

https://codepen.io/anon/pen/zyJZbr

<svg id="rootSVGBox" width="1242" height="2688" viewBox="0 0 1242 2688">
  <foreignObject width="100%" height="100%">
    <div id="testBox" style="width: 100%; height: 100%; background:#00B9FC" xmlns="http://www.w3.org/1999/xhtml">
      Why is this height wrong?
    </div>
  </foreignObject>
</svg>

标签: htmlsvg

解决方案


在 Firefox 中,您的示例有效。
在旁注中,这个问题通过将 div 绝对定位在 svg 元素内提供了一个解决方案:

#testBox {
  position:absolute;
}
<svg id="rootSVGBox" width="1242" height="2688" viewBox="0 0 1242 2688">
   <foreignObject width="100%" height="100%">
      <div id="testBox" style="width: 100%; height: 100%; background:#00B9FC" xmlns="http://www.w3.org/1999/xhtml">
        This is 100% height.
      </div>
   </foreignObject>
</svg>


推荐阅读