css制作树形菜单
使用嵌套列表和CSS样式
HTML结构使用无序列表<ul>和列表项<li>嵌套实现树形层级:
<ul class="tree">
<li>父节点1
<ul>
<li>子节点1</li>
<li>子节点2</li>
</ul>
</li>
<li>父节点2</li>
</ul>
CSS通过控制子菜单的显示/隐藏实现折叠效果:
.tree ul {
display: none; /* 默认隐藏子菜单 */
padding-left: 20px;
}
.tree li {
list-style-type: none;
position: relative;
}
.tree input[type="checkbox"] {
position: absolute;
opacity: 0;
}
.tree input:checked ~ ul {
display: block; /* 展开状态显示 */
}
添加交互控制元素
在HTML中添加复选框控制展开/折叠:
<li>
<label>
<input type="checkbox"> 节点名称
</label>
<ul>...</ul>
</li>
CSS美化复选框和连接线:
.tree label:before {
content: "+";
margin-right: 5px;
}
.tree input:checked ~ label:before {
content: "-";
}
.tree ul {
border-left: 1px dotted #ccc;
}
纯CSS实现方案
不使用JavaScript的替代方案:
.tree li {
cursor: pointer;
}
.tree li:before {
content: "►";
font-size: 10px;
color: #666;
}
.tree li.open:before {
content: "▼";
}
.tree li.open > ul {
display: block;
}
动画效果增强
添加平滑过渡效果:
.tree ul {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
}
.tree input:checked ~ ul {
max-height: 1000px;
}
响应式设计考虑
确保移动端可用性:

@media (max-width: 768px) {
.tree {
font-size: 14px;
}
.tree ul {
padding-left: 15px;
}
}






