一、CSS 计数器
- counter-reset - 创建或者重置计数器
- counter-increment - 递增变量
- content - 插入生成的内容
- counter() 或 counters() 函数 - 将计数器的值添加到元素
使用
- 在元素父级创建一个计数器
.list {
counter-reset: count;
}
- 子级中使用伪类显示数量
.item::after {
counter-increment: count;
content: counter(count);
}
二、实践
先预览一下吧
CSS代码
* {
margin: 0;
padding: 0;
}
.list {
position: relative;
display: grid;
grid-template-columns: repeat(3, 95px);
grid-template-rows: repeat(3, 95px);
gap: 5px;
width: 300px;
margin: 30px auto;
list-style: none;
padding: 0;
/*初始化*/
counter-reset: count;
}
.item {
/*宽高比1:1*/
aspect-ratio: 1;
background-color: #f0f0f0;
}
.image {
width: 100%;
height: 100%;
display: none;
}
.item::after {
display: grid;
height: 95px;
place-content: center;
font-size: 30px;
color: #ffffff;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.item:nth-child(9)~.item {
/*
选择第9个以后的元素
从第9个以后的元素开始计数
使用 visibility: hidden 将其隐藏
这里注意不能使用 display: none
使用 display 就不会触发计数器计数了
*/
visibility: hidden;
counter-increment: count;
position: absolute;
right: 0;
bottom: 0;
width: 95px;
height: 95px;
margin-right: 5px;
}
.item:nth-child(9)~.item:last-child::after {
/* 最后一个元素显示出来 */
visibility: visible;
background-color: rgba(0, 0, 0, .1);
}
.item:nth-child(9)~.item::after {
/*
选择第9个以后的元素
给伪类添加内容
*/
content: "+"counter(count);
}
HTML页面代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>九宫格</title>
</head>
<body>
<div>
<ul class="list">
<li class="item"><img src="static/basic.png" alt="" class="image"></li>
<li class="item"><img src="static/basic-default.png" alt="" class="image"></li>
<li class="item"><img src="static/canvas.png" alt="" class="image"></li>
<li class="item"><img src="static/canvas-default.png" alt="" class="image"></li>
<li class="item"><img src="static/function.png" alt="" class="image"></li>
<li class="item"><img src="static/function-default.png" alt="" class="image"></li>
<li class="item"><img src="static/hammer.png" alt="" class="image"></li>
<li class="item"><img src="static/hammer-default.png" alt="" class="image"></li>
<li class="item"><img src="static/component_select.png" alt="" class="image"></li>
<li class="item"><img src="static/component.png" alt="" class="image"></li>
<li class="item"><img src="static/js_select.png" alt="" class="image"></li>
<li class="item"><img src="static/js.png" alt="" class="image"></li>
<li class="item"><img src="static/min_button_select.png" alt="" class="image"></li>
<li class="item"><img src="static/min_button.png" alt="" class="image"></li>
<li class="item"><img src="static/template_select.png" alt="" class="image"></li>
<li class="item"><img src="static/template.png" alt="" class="image"></li>
</ul>
</div>
</body>
</html>