Loading...
Loading...
- 最后编辑:2025/10/19 15:13:26 -
Loading...
今天心血来潮,写了个登录页面的简单案例来练手,没想到在这短短一个小时不到的时间中,就让我偶然学到了一个关于css伪类的小知识。

如图,我在做这个页面时,想让输入框的下方加一个下边框,获得焦点后变换颜色。
按照常见的解决思路,我有两种方案可选:
::after伪类达到“伪边框”的效果。经过一番考虑后,我决定采用第二种方法。
但是真正实践起来的时候,我却发现input:after这个伪类无法正常生效。我一开始以为是我的代码有问题导致的,但我尝试了几次后,问题依然存在。
由此,我便去百度搜索了一下相关的问题,没想到这一搜,还真给我搜到了类似的问题:为什么input不支持伪元素(:after,:before)? - 知乎。
问题的根本原因在于::before和::after伪类本质上是一个元素的子元素,而子元素是需要插进父元素标签中的,也就是说这类标签本身需要是一个容器,但诸如<input>、<img>、<iframe>等标签本身并不支持插入子元素,或者说,它们没有能够插入子元素的空间,也无法容纳其他元素,因此伪类在这些标签上并不能正常生效。
这里引用一段W3C规范的说明:
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.
由此可见,伪类在某些标签上并不能正常生效,因此我们在开发中应尽量避免出现这种错误的写法。
如果出现这种需要在这些标签上添加伪类的需求,可以考虑用<div>标签包裹后,直接将伪类定位到它身上。
以下是错误示范:
<style>
.input::after {
content: "";
/* other styles... */
}
</style>
<input class="input" value="This is a input example" />若要实现类似的样式,应将代码修改为以下的形式:
<style>
.input-container::after {
content: "";
/* other styles... */
}
</style>
<div class="input-container">
<input class="input" value="This is a input example" />
</div>如此修改后,伪类便能够正常生效了。
6天前