伪元素

288 阅读1分钟

伪元素

css3新增了“伪元素”特性,顾名思义,表示虚拟动态创建的元素。

伪元素用双冒号表示,IE8可以兼容单冒号。

::before 和 ::after

::before 创建一个伪元素,其将成功匹配选中的元素的第一个子元素,在所选择的元素内容前面添加内容,使用content属性。并且可以进行查出内容的相关属性的设置。

<!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>Document</title>
    <style>
        li {
            list-style:none;
        }
        li:before {
            content:"*";
        }
    </style>
</head>
<body>
    <ul>
        <li>我是第一</li>
        <li>我是第二</li>
        <li>我是第三</li>
        <li>我是第四</li>
    </ul>
</body>
</html>

::after 创建一个伪元素,其将成功匹配选中的元素的最后一个子元素。在所选择的元素内容后面添加内容,使用content属性。并且可以进行查出内容的相关属性的设置。

<!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>Document</title>
</head>
<style>
    p:after {
        content:"(备注)";
        color:red;
    }
</style>
<body>
    <p>这是一段文字</p>
</body>
</html>


::selection伪元素

::selection css伪元素应用于文档中被高亮的部分(使用鼠标圈选的部分)

<!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>Document</title>
    <style>
        div {
            border: 1px solid #000;
            width:300px;
            height:300px;
        }
        .box1::selection {
            background-color:salmon;
            color:slateblue;
        }
    </style>
</head>
<body>
    <div class="box1">
        文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字
        文字文字文字文字文字文字文字文字文字
    </div>
</body>
</html>

::first-letter 和 ::first-line

::first-letter 会选中某元素中(必须是块级元素)第一行的第一个元素

::first-line 会选中某元素中(必须是块级元素)第一行的全部文字

<!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>Document</title>
    <style>
        div {
            border: 1px solid #000;
            width:300px;
            height:300px;
        }

        .box1::first-letter {
            font-size :50px;
        }
        .box1::first-line {
            /* 添加下划线 */
            text-decoration:underline;
        }
    </style>
</head>
<body>
    <div class="box1">
        文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字
        文字文字文字文字文字文字文字文字文字
    </div>
</body>
</html>