如何将 HTML 元素放在内联 SVG 上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33313602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to place HTML elements over inline SVG
提问by Alan De Smet
I'm able to use z-index to put various HTML elements over each other in whatever order I like, except when one of the elements in an inline SVG. For example, given the HTML
我可以使用 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>
and the matching CSS
和匹配的 CSS
p {
width: 200px;
z-index:10;
}
div {
position: relative;
}
svg {
position: absolute;
left: 0;
top: 0;
z-index: 1;
}
no matter how I order the two or adjust the z-index, the inline SVG renders on top of the text. How can I get the SVG behind the text?
无论我如何对两者进行排序或调整 z-index,内联 SVG 都会呈现在文本之上。如何在文本后面获取 SVG?
The example above is available at https://jsfiddle.net/o0n10j78/1/.
上面的示例可在https://jsfiddle.net/o0n10j78/1/ 获得。
If it's relevant, in my actual application I'm generating nearly all of the document structure in Javascript with the assistance of jQuery, including the inline SVG and the HTML block I wish to have in front of it.
如果相关,在我的实际应用程序中,我在 jQuery 的帮助下用 Javascript 生成几乎所有文档结构,包括内联 SVG 和我希望在它前面的 HTML 块。
回答by Hoshts
The z-index property is only being applied on positioned elements. Adding position: relative;
to the paragraph tag will correctly apply it.
z-index 属性仅应用于定位元素。添加position: relative;
到段落标签将正确应用它。
Look at this pagefor a full reference of the property.
查看此页面以获取该属性的完整参考。
On a side note: As I first wrote in a comment, setting the svg z-index to -1 works as it lowers the priority of the element below the default that all elements have. This comes with the downside that the svg actually being placed behind the div as well. Try apply a background color to the div while having the svg z-index set to -1.
附带说明:正如我第一次在评论中所写,将 svg z-index 设置为 -1 会起作用,因为它将元素的优先级降低到所有元素具有的默认值以下。这带来了 svg 实际上也被放置在 div 后面的缺点。尝试将背景颜色应用于 div,同时将 svg z-index 设置为 -1。
回答by Fazil Abdulkhadar
Please add a z-index:-1
to the svg.
请z-index:-1
在 svg 中添加一个。
svg {
position: absolute;
left: 0;
top: 0;
z-index: -1;
}