css 制作目录
CSS 制作目录的方法
使用 CSS 制作目录可以通过多种方式实现,以下是几种常见的方法:
使用无序列表和样式调整
通过 HTML 的无序列表 <ul> 和 <li> 结合 CSS 样式可以创建简单的目录结构。

<ul class="toc">
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
</ul>
.toc {
list-style-type: none;
padding-left: 0;
}
.toc li {
margin-bottom: 8px;
}
.toc a {
text-decoration: none;
color: #333;
}
.toc a:hover {
text-decoration: underline;
}
使用计数器自动编号
通过 CSS 计数器可以实现目录的自动编号,适合多级目录结构。
<div class="toc">
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
<a href="#section3">Section 3</a>
</div>
.toc {
counter-reset: section;
}
.toc a {
display: block;
text-decoration: none;
color: #333;
margin-bottom: 8px;
}
.toc a::before {
counter-increment: section;
content: counter(section) ". ";
}
多级嵌套目录
对于复杂的多级目录,可以使用嵌套列表和 CSS 控制缩进和样式。

<ul class="toc">
<li><a href="#section1">Section 1</a>
<ul>
<li><a href="#subsection1">Subsection 1</a></li>
<li><a href="#subsection2">Subsection 2</a></li>
</ul>
</li>
<li><a href="#section2">Section 2</a></li>
</ul>
.toc {
list-style-type: none;
padding-left: 0;
}
.toc ul {
list-style-type: none;
padding-left: 20px;
}
.toc a {
text-decoration: none;
color: #333;
}
.toc a:hover {
text-decoration: underline;
}
使用 Flexbox 或 Grid 布局
Flexbox 或 Grid 可以用于创建更灵活的目录布局,适合横向或特殊排列需求。
<div class="toc">
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
<a href="#section3">Section 3</a>
</div>
.toc {
display: flex;
gap: 16px;
}
.toc a {
text-decoration: none;
color: #333;
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
}
.toc a:hover {
background-color: #f0f0f0;
}
添加动态效果
通过 CSS 过渡或动画可以为目录添加悬停或点击效果,提升交互体验。
.toc a {
transition: background-color 0.3s ease;
}
.toc a:hover {
background-color: #e0e0e0;
}
以上方法可以根据实际需求灵活组合,实现不同风格的目录效果。






