css 伪类/伪元素

95 阅读1分钟

前言:css中有伪类伪元素的概念;听起来差不多,但是两者分别代表什么,有什么区别呢?

1.定义

伪类:伪类是用于向某些选择器添加特殊效果的;伪类的效果可以通过添加实际的类来实现;

伪元素:伪元素是用于将特殊的效果添加到某些选择器的,伪对象的效果可以通过添加实际的元素来实现

2.选择符

伪类:

image.png

伪元素:

image.png

3.实例

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> CSS 伪类</title>
</head>

<style>
    /* 使用伪类改变第一个p标签的颜色 */
    p:first-child {
        color: red;
    }
</style>

<body>
    <div>
        <p>我是第一个p标签</p>
        <p>我是第二个p标签</p>
    </div>
</body>

</html>

如上代码,我们通过伪类改变第一个p标签颜色。如果不使用伪类呢?看下面

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> CSS 伪类</title>
</head>

<style>
    /* 使用伪类改变第一个p标签的颜色
    p:first-child {
        color: red;
    } */
    /* 使用类名改变第一个p标签的颜色 */
    .first-child{
        color: red;
    }
</style>

<body>
    <div>
        <p class="first-child">我是第一个p标签</p>
        <p>我是第二个p标签</p>
    </div>
</body>

</html>

显而易见,使用伪类可以少写class。那么此效果用伪元素怎么实现呢?

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> CSS 伪类</title>
</head>

<style>
    /* 使用伪类改变第一个p标签的颜色
    p:first-child {
        color: red;
    } */
    /* 使用类名改变第一个p标签的颜色 */
    /* .first-child{
        color: red;
    } */

    p::first-letter {
        color: red;
    }
</style>

<body>
    <div>
        <p>我是第一个p标签</p>
        <p>我是第二个p标签</p>
    </div>
</body>

</html>

如果不用伪元素我们怎么做呢?

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> CSS 伪类</title>
</head>

<style>
    /* 使用伪类改变第一个p标签的颜色
    p:first-child {
        color: red;
    } */
    /* 使用类名改变第一个p标签的颜色 */
    /* .first-child{
        color: red;
    } */

    /* p::first-letter {
        color: red;
    } */
    p span {
        color: red;
    }
</style>

<body>
    <div>
        <p>
            <span>我是第一个p标签</span>
        </p>
        <p>我是第二个p标签</p>
    </div>
</body>

</html>

4. 区别

通过上述实例验证,就可以看出二者区别

  • 伪类的效果可以通过添加实际的类来实现
  • 伪元素的效果可以通过添加实际的元素来实现
  • 所以它们的本质区别就是是否抽象创造了新元素

值得注意的是:

伪类只能使用: 伪元素可以使用:也可以使用::,前者是css2的后者是css3的

因为伪类是类似于添加类所以可以是多个,而伪元素在一个选择器中只能出现一次,并且只能出现在末尾