I'm particularly interested in understanding when the ::before
and ::after
pseudo-elements can be applied to self-closing tags. This is the definition of these pseudo-elements, according to the W3 Generated Content CSS Specifications:
12.1 The :before and :after pseudo-elements: Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content. The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.
Based on this, it seems that these pseudo-elements are intended to modify the content of an element. As I understand it (although I can't find an authoritative source to support this), "content" is defined more or less as "the stuff between the opening and closing tags"; therefore, I would think that elements which have no "content" (such as an HTML br
tag) should not support the ::before
and ::after
pseudo-elements.
Extrapolating on this, and based on my understanding of the definition of an element's "content", I would think that none of the self-closing tags would support the ::before
and ::after
pseudo-elements. In practice, however, I've found that many self-closing tags have full support.
Aside from the question of what is defined as "content", we can also consider the fact that pseudo-elements are represented as (although technically they aren't) DOM children of the element to which they are applied. The fact that self-closing tags cannot have DOM children seems to support the idea that self-closing tags oughtn't have pseudo-elements.
In my attempt to find the answer to this question, I put together a small test to determine which self-closing tags (I picked a handful of them as they came to mind) support ::before
and ::after
, and I've embedded that test in a snippet below. I am getting radically different results across browsers and can find very little consistency.
.test {
display: inline;
visibility: hidden;
}
span + *::after {
visibility: visible;
color: green;
content: 'YES';
}
<h3>Which Self-Closing Tags Support Pseudo Elements?</h3>
<div><span>Text Input:</span> <input type="text" class="test"></div>
<div><span>Checkbox Input:</span> <input type="checkbox" class="test"></div>
<div><span>Radio Input:</span> <input type="radio" class="test"></div>
<div><span>Submit Input:</span> <input type="submit" class="test"></div>
<div><span>Reset Input:</span> <input type="reset" class="test"></div>
<div><span>Button Input:</span> <input type="button" class="test"></div>
<div><span>Image:</span> <img class="test"></div>
<div><span>Line Break:</span> <br class="test"></div>
<div><span>Horizontal Rule:</span> <hr class="test"></div>
<div><span>Link:</span> <link class="test"></div>
<div><span>Meta:</span> <meta class="test"></div>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…