html css制作树
HTML和CSS制作树形结构
使用HTML和CSS可以创建树形结构,通常用于展示层级关系,如组织结构图、文件目录等。以下是几种实现方法:
使用无序列表嵌套

<div class="tree">
<ul>
<li>
<span>根节点</span>
<ul>
<li><span>子节点1</span></li>
<li><span>子节点2</span></li>
</ul>
</li>
</ul>
</div>
.tree ul {
padding-left: 20px;
list-style: none;
}
.tree li {
position: relative;
margin: 0;
padding: 5px 0;
}
.tree li::before {
content: "";
position: absolute;
top: 0;
left: -15px;
width: 15px;
height: 1px;
background: #000;
}
.tree li:first-child::after {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: -15px;
width: 1px;
background: #000;
}
使用Flexbox布局

<div class="tree">
<div class="node">根节点</div>
<div class="children">
<div class="tree">
<div class="node">子节点1</div>
</div>
<div class="tree">
<div class="node">子节点2</div>
</div>
</div>
</div>
.tree {
display: flex;
flex-direction: column;
align-items: center;
}
.node {
padding: 5px 10px;
border: 1px solid #ccc;
margin-bottom: 5px;
}
.children {
display: flex;
position: relative;
}
.children::before {
content: "";
position: absolute;
top: -5px;
left: 50%;
width: 1px;
height: 5px;
background: #000;
}
.tree + .tree::before {
content: "";
position: absolute;
top: -5px;
left: 0;
right: 50%;
height: 1px;
background: #000;
}
使用伪元素连接节点
.tree li {
position: relative;
padding-left: 30px;
}
.tree li::before {
content: "";
position: absolute;
left: 15px;
top: 0;
width: 1px;
height: 100%;
background: #999;
}
.tree li::after {
content: "";
position: absolute;
left: 15px;
top: 50%;
width: 15px;
height: 1px;
background: #999;
}
.tree li:last-child::before {
height: 50%;
}
添加交互效果
可以为树形结构添加展开/折叠功能:
.tree input[type="checkbox"] {
display: none;
}
.tree label {
cursor: pointer;
}
.tree input ~ ul {
display: none;
}
.tree input:checked ~ ul {
display: block;
}
<div class="tree">
<input type="checkbox" id="node1" checked>
<label for="node1">根节点</label>
<ul>
<li>子节点1</li>
<li>子节点2</li>
</ul>
</div>
这些方法可以根据需要组合使用,调整样式和结构以满足具体的设计需求。






