<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>美观的纯 CSS 折叠列表</title>
<style>
body {
font-family: Arial, sans-serif;
}
ul {
list-style-type: none;
/* 去掉默认列表样式 */
padding: 0;
/* 去掉内边距 */
}
li {
margin: 5px 0;
position: relative;
/* 为箭头定位 */
padding-left: 25px;
/* 给箭头留出空间 */
}
input[type="checkbox"] {
display: none;
/* 隐藏复选框 */
}
label {
cursor: pointer;
/* 鼠标指针变为手型 */
position: relative;
/* 让伪元素相对定位 */
padding-left: 15px;
/* 文字与箭头的间距 */
}
/* 使用伪元素绘制箭头 */
label:before {
content: "";
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%) rotate(-45deg);
width: 4px;
height: 4px;
border: solid black;
border-width: 0 2px 2px 0;
display: inline-block;
transition: transform 0.2s;
}
input[type="checkbox"]:checked+label:before {
transform: translateY(-50%) rotate(46deg);
/* 展开时旋转箭头 */
}
.children {
display: none;
/* 默认隐藏子元素 */
padding-left: 15px;
/* 子级项缩进 */
}
input[type="checkbox"]:checked~.children {
display: block;
/* 展开时显示子元素 */
}
</style>
</head>
<body>
<h1>美观的纯 CSS 折叠列表</h1>
<ul>
<li>
<input type="checkbox" id="parent1">
<label for="parent1">父级 1</label>
<ul class="children">
<li>
<input type="checkbox" id="child1-1">
<label for="child1-1">子级 1-1</label>
<ul class="children">
<li>子级 1-1-1</li>
<li>子级 1-1-2</li>
</ul>
</li>
<li>
<input type="checkbox" id="child1-2">
<label for="child1-2">子级 1-2</label>
<ul class="children">
<li>子级 1-2-1</li>
<li>子级 1-2-2</li>
</ul>
</li>
</ul>
</li>
<li>
<input type="checkbox" id="parent2">
<label for="parent2">父级 2</label>
<ul class="children">
<li>
<input type="checkbox" id="child2-1">
<label for="child2-1">子级 2-1</label>
</li>
<li>
<input type="checkbox" id="child2-2">
<label for="child2-2">子级 2-2</label>
</li>
</ul>
</li>
</ul>
</body>
</html>