::before 用来将内容插入到元素的前面
::after 用来将内容插入到元素的后面
::before 和::after 中有一个 content() 属性用来生成内容。
- <style type="text/css">
- .item::before{
- content : 'Hello ';
- }
- .item::after{
- content : " world"
- }
- </style>
- <div class="item">item</div>
运行效果如下:
需要注意的是,大部分浏览器将这两个伪元素默认以行内元素显示,有了这两个伪元素可以减少对标签的使用。
CSS 有一个计数功能,就像使用变量一样,它有以下 4 个属性:
counter-reset 创建或重置计数器;需要注意的是:当第一次使用 counter-reset 时,表示创建;当第二次使用时,表示重置,但需要注意的是,是同一个元素才会重置。
counter-increment 增长计数器;
content 生成内容;
counter() 将计数器的值添加到元素中。
接下来,看一个最简单的计数器示例:
- <style type="text/css">
- ul{ list-style:none; counter-reset : num; } ul li::before{ counter-increment
- : num; content : 'List-' counter(num) '-item '; }
- </style>
- <ul>
- <li>
- AAAAAAAA
- </li>
- <li>
- BBBBBBBB
- </li>
- <li>
- CCCCCCCC
- </li>
- </ul>
运行效果如下:
它不是根据元素的个数来计算值的,而是根据 counter-increment 的数量来计算的。
再看一个,稍微复杂点的示例:
- <style type="text/css">
- body{
- counter-reset : num1;
- }
- h1::before{
- counter-increment : num1;
- content : 'The ' counter(num1) ' ';
- }
- h1{
- counter-reset : num2;
- }
- h2::before{
- counter-increment : num2;
- content : 'content ' counter(num1) '.' counter(num2);
- }
- </style>
- <h1>Title</h1>
- <h2>这是一段内容。</h2>
- <h2>这是一段内容。</h2>
- <h1>Title</h1>
- <h2>这是一段内容。</h2>
- <h1>Title</h1>
- <h2>这是一段内容。</h2>
- <h2>这是一段内容。</h2>
- <h2>这是一段内容。</h2>
运行结果如下:
利用计数器来实现获取 input checked 选择的数量。
- <style type="text/css">
- body{
- counter-reset : num;
- }
- input:checked{
- counter-increment : num;
- }
- p::after{
- content : counter(num) '个'
- }
- </style>
- <body>
- CSS3<input type="checkbox">
- html5<input type="checkbox">
- Javascript<input type="checkbox">
- <p>你一共选择了</p>
- </body>
运行结果如下所示:
可以手动更改 counter-increment 数值大小:
- <style type="text/css">
- body{
- counter-reset : num;
- }
- input:nth-of-type(1):checked{
- counter-increment : num 5;
- }
- input:nth-of-type(2):checked{
- counter-increment: num 2;
- }
- input:nth-of-type(3):checked{
- counter-increment:num 7;
- }
- input:nth-of-type(4):checked{
- counter-increment: num 1;
- }
- p::after{
- content : 'Count: ' counter(num)
- }
- </style>
- <body>
- 5<input type="checkbox">
- 2<input type="checkbox">
- 7<input type="checkbox">
- 1<input type="checkbox">
- <p></p>
- </body>
运行结果如下:
在 content 中还有两个值:
attr() 插入标签属性值;
url() 插入一个外部资源 (图片,音频,视频或浏览器支持的其它任何资源)。
- <style type="text/css">
- .box a{
- position:relative;
- }
- .box a img{
- width:200px;
- }
- .box a::after{
- content : attr(title);
- position:absolute;
- bottom:0;
- left:0;
- width:100%;
- height:25px;
- line-height:25px;
- text-align:center;
- background-color:#ccc;
- color:#fff;
- }
- </style>
- <body>
- <div class="box">
- <a href="javascript:;" title="这是一个logo">
- <img src="images/logo.png">
- </a>
- </div>
- </body>
运行结果如下:
伪元素的意义就在于它可以使 HTML 更加语义化。有时候为了某些效果,不得不添加一些没有意义的标签,而这两个伪元素既能起到这种辅助布局的作用,又不需要添加没有意义的标签。
来源: https://juejin.im/post/5a3f6d086fb9a0451969cd5c