CSS :before on inline SVG

标签 css html svg pseudo-element

更新
感谢 porneL 指出生成内容和替换元素之间的关系。
我找到了 this article处理这个主题:

有趣的是,一份名为“CSS3 生成和替换的内容模块”(11 年前!)的 W3C 文档定义了伪元素 :outside,它可以提供一种使用生成内容的解决方案替换元素,通过将生成的内容放在替换元素之外,而不是尝试将其附加到里面。


原始问题

有没有办法使用 CSS :before:after 伪元素来设置内联 SVG 元素的样式?

示例:http://jsfiddle.net/wD56Q/

在此示例中,使用 :before 定义的样式未应用于 SVG(已在 Firefox 29 和 Chrome 35 中测试)。 是关于 :before 中的 content 属性吗?根据我的阅读,它尝试在元素中插入生成的内容。SVG 是否会失败?


来自 MDN 的相关文档:

::before (:before)

::before creates a pseudo-element that is the first child of the element matched. Often used to add cosmetic content to an element, by using the content property. This element is inline by default.

content

The content CSS property is used with the ::before and ::after pseudo-elements to generate content in an element. Objects inserted using the content property are anonymous replaced elements.


例子中的代码:

   svg {
     left: 50px;
     position: absolute;
     top: 50px;
   }
   svg circle {
     fill: green;
   }
   svg:before {
     border: 2px solid blue;
     content: "";
     height: 100px;
     margin: -6px;
     padding: 4px;
     position: absolute;
     width: 100px;
     z-index: -1;
   }
   div {
     background-color: green;
     height: 100px;
     left: 200px;
     position: absolute;
     top: 150px;
     width: 100px;
   }
   div:before {
     border: 2px solid blue;
     content: "";
     height: 100px;
     margin: -6px;
     padding: 4px;
     position: absolute;
     width: 100px;
     z-index: -1;
   }
<svg height="100" width="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="50" />
</svg>

<div></div>

最佳答案

不,内联 SVG 被视为图像,图像是替换元素,不允许生成内容

严格来说,我认为它是未定义的。 CSS 2.1只是一般性地谈论“图像、嵌入式文档和小程序”和The HTML standard为图像定义它,但没有明确定义 SVG。

关于CSS :before on inline SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51134612/

相关文章:

javascript - 在 Hover 上只改变一个 Div 从几个相同的类

html - 使用外部 CSS 样式表设置 SVG 行的样式

html - 为什么 SVG 过滤器不适用于我的代码中的 HTML 元素?

javascript - 将 D3 链接文本显示在右侧

html - 内容超出屏幕 div 的 100%

html - 如何在不创建图像元素的情况下将图像叠加在元素上?

javascript - 防止文本在输入框中移动

python - 在理解 BeautifulSoup 过滤时遇到问题

javascript - 如何让函数等待事件发生?

javascript - 当 DIV 从 IE8 中的光标下方移动时,悬停样式保持不变