css 伪元素 实例详解

(1)伪元素是什么

我们平时在写网页时,经常会遇到这种情况:想给一段文字的第一个字设置一个单独的样式?给一个div前面添加一个简单的内容?遇到这样的问题时,我们可以添加html标签,设置css样式来实现,但是,如果我们了解伪元素,相信你会常用它的。

伪元素控制的内容实际上和元素是相同的,但是它本身只是基于元素的抽象,并不存在于文档中,所以叫伪元素。

(2)伪元素有哪些

  1. :first-letter
    伪元素的样式将应用于元素文本的第一个字(母)。

  2. :first-line
    伪元素的样式将应用于元素文本的第一行。

  3. :selection 伪元素的样式将应用于被选中的部分

  4. :before
    在元素内容的最前面添加新内容。

  5. :after
    在元素内容的最后面添加新内容。

**为了和伪类区别,建议在写伪元素的时候,用两个冒号**

(3)用法

首先我创建了一个背景蓝色的div,内容为九寨沟的介绍

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wei-blog</title>
    <style >
        .box{
            width: 200px;
            height: 200px;
            background-color: skyblue;
        }
    </style>
</head>
<body>
    <div class="box">
        九寨沟国家级自然保护区位于四川省阿坝藏族羌族自治州九寨沟县境内,是中国第一个以保护自然风景为主    要目的的自然保护区。
    </div>
</body>
</html>

效果:

:first-letter

代码:
CSS

.box::first-letter{
    font-size: 25px;
}

结果:

:first-line

代码:
CSS

.box::first-line{
    font-size: 25px;
}

结果:

:selection

代码:
CSS

.box::selection{
    color:white;
    background-color: black
}

结果:

:before

before是在元素之前添加内容,要特别注意写上 content:’’;

下面的例子我将在原蓝色div之前添加一个橘色块

代码:
CSS

.box{
    width: 200px;
    height: 200px;
    background-color: skyblue;
    position: relative;
    margin-left: 200px;
}
.box::before{
    content: '';
    display: block;
    width:100px;
    height: 200px;
    background-color: orange;
    position: absolute;
    left: -100px;
}

结果:

:after

after跟before相反,也要特别注意写上 content:’’;
下面的例子我将在蓝色div后添加一个灰色块

代码:
CSS

<style >
    .box{
        width: 200px;
        height: 200px;
        background-color: skyblue;
        position: relative;
        margin-left: 200px;
    }
    .box::before{
        content: '';
        display: block;
        width:100px;
        height: 200px;
        background-color: orange;
        position: absolute;
        left: -100px;
    }
    .box::after{
        content: '';
        display: block;
        width:100px;
        height: 200px;
        background-color: #ccc;
        position: absolute;
        right:-100px;
        top:0;
    }
</style>

结果: