css中伪类和伪元素

伪类和伪元素时对那些我们不能通过class、id等选择元素的补充

伪类的操作对象是文档树中已有的元素(可以给已有元素加了一个类替代),而伪元素则创建了一个文档数外的元素(可以添加一个新元素替代)

CSS3规范中要求使用双冒号(::)表示伪元素,以此来区分伪元素和伪类。

伪类:

<p>
    <em>This</em>
    <em>is a text</em>
</p>
em:first-child {
    color: red;
}

first-child是对已有元素em的修饰,意思是修饰标签为em同时是父元素的第一个子元素的元素,注意不是em标签下的第一个子元素

效果等同于:

<p>
    <em class="first-child">This</em>
    <em>is a text</em>
</p>
em.first-child {
    color: red;
}

伪元素:

<p>
    <em>This</em>
    <em>is a text</em>
</p>
p::first-letter {
    color: red;
}

first-letter相当于在p里面新造了一个元素,效果等同:

<p>
    <em><span>T</span>his</em>
    <em>is a text</em>
</p>
p span {
    color: red;
}