原文:Why CSS ::before doesn’t work on inputs and images
无法将CSS伪元素::before
和::after
添加到文本输入框和图片,因为这些元素是“替换元素”,这是HTML标准“Rendering section”中定义的特殊类别:
The following elements can be replaced elements:
<audio>
,<canvas>
,<embed>
,<iframe>
,<img>
,<input>
,<object>
, and<video>
.
CSS工作组成员fantasai在GitHub上解释了原因:
Replaced elements replace all the content of the element, including ::before and ::after pseudo-elements. That’s why it doesn’t work on them.
替换元素将替换元素的所有内容,包括::before
和::after
伪元素。这就是为什么伪元素对他们不起作用的原因。
例如,在<img>
元素上不能使用::before
来显示图像的替代文本–这种方法可以在其他元素上使用:
1 | /* This doesn't work! */ |
注意:取决于浏览器和其他因素,<img>
元素不一定总是替换元素。 例如,如果图像无法加载,则在Chrome
和Firefox
中可以将::before
和::after
添加到<img>
中:Styling Broken Images(翻译:给破碎图片添加样式)。
对于表单控件,情况尚不清楚。 <input>
和<textarea>
元素被视为“半替换”元素,这是CSS规范编辑者Tab Atkins在GitHub上的工作组讨论中使用的一个术语:
All input types are at least “semi-replaced.” We’re still not really sure how that state works; it’s not fully a replaced element (it doesn’t size like one, and responds to some properties), but still has some notion of an “intrinsic” size that it likes to obey (unlike normal elements) and is unbreakable.
是否可以将CSS::before
和::after
内容添加到input中,取决于input类型和浏览器。 例如,Chrome
和Safari
的复选框和单选按钮支持CSScontent
。
1 | input::before { |
demo: CSS ::before content on a native checkbox in Chrome
如果你无法在元素上使用CSS::before
或::after
内容,请记得检查元素是否为(半)替换元素。