【问题标题】:How to place HTML elements over inline SVG如何将 HTML 元素放置在内联 SVG 上
【发布时间】:2016-01-23 15:42:58
【问题描述】:

我可以使用 z-index 以我喜欢的任何顺序将各种 HTML 元素相互叠加,但内联 SVG 中的元素之一除外。例如,给定 HTML

<div>
    <p>Text before SVG. I'm some boring text. Such incredibly boring text. Who would possibly want to read such boring text?</p>
    <svg version="1.1" baseProfile="full" width="200" height="200" xmlns="http://www.w3.org/2000/svg">
        <circle cx="75" cy="40" r="20" fill="red" />
    </svg>
</div>
<div>
    <svg version="1.1" baseProfile="full" width="200" height="200" xmlns="http://www.w3.org/2000/svg">
        <circle cx="75" cy="75" r="20" fill="red" />
    </svg>
    <p>SVG before text. I'm some boring text. Such incredibly boring text. Who would possibly want to read such boring text?</p>
</div>

和匹配的 CSS

p {
    width: 200px;
    z-index:10;
}
div {
    position: relative;
}
svg {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
}

无论我如何对这两者排序或调整 z-index,内联 SVG 都会呈现在文本之上。如何获取文本背后的 SVG?

以上示例可在https://jsfiddle.net/o0n10j78/1/ 获得。

如果它是相关的,在我的实际应用程序中,我在 jQuery 的帮助下用 Javascript 生成几乎所有的文档结构,包括内联 SVG 和我希望在它前面的 HTML 块。

【问题讨论】:

  • 尝试将svg的z-index设置为-1
  • 行得通,谢谢!现在......为什么它会起作用?如果您只是将您的评论扔进答案中,我会投赞成票,如果没有更好的答案,我会在几天内接受它。但是,我很乐意接受一个回答,告诉我为什么它会以这种方式运行,这样我就可以改进我对这种情况的心理模型。我特别不明白为什么它适用于兄弟姐妹,比如 p。
  • 问题实际上不是这里的svg,而是p-tag。 Z-index 不适用于元素,因为它没有设置位置。在 svg 上设置 -1 的替代方法,设置 position: relative 在 P-tag 上。我没有注意到那个位置丢失了。

标签: html css svg


【解决方案1】:

z-index 属性仅应用于定位元素。将position: relative; 添加到段落标签将正确应用它。

查看this page 以获取该属性的完整参考。

附带说明:正如我第一次在评论中所写,将 svg z-index 设置为 -1 会起作用,因为它会将元素的优先级降低到低于所有元素的默认值。这带来了 svg 实际上也被放置在 div 后面的缺点。尝试将背景颜色应用于 div,同时将 svg z-index 设置为 -1。

【讨论】:

    【解决方案2】:

    请在 svg 中添加 z-index:-1

    svg {
        position: absolute;
        left: 0;
        top: 0;
        z-index: -1;
    }
    

    【讨论】:

      【解决方案3】:

      按照 Fazil Abdulkhadar 的建议添加 z-index: -1 对我不起作用,因为我有背景。因此,我的 svg 将成为我的背景。

      按照 Hoshts 的建议,我将 position: relative; 放在我想要的元素上在我的绝对 svg 前面

      对于这个问题的例子,它将是:

      p {
         position: relative; // add it
         width: 200px;
         /* z-index: 10; */ // change it to z-index: 1;
      }
      div {
         position: relative; // not sure it is necessary
      }
      svg {
         position: absolute;
         left: 0;
         top: 0;
         /* z-index: 1; */ // remove it
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-07
        • 1970-01-01
        • 1970-01-01
        • 2017-09-16
        • 2021-11-29
        • 2017-11-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多