css 制作目录
CSS 制作目录的方法
使用 CSS 可以轻松为网页内容创建美观且功能性的目录。以下是几种常见方法:
使用 ul 和 li 创建基础目录结构
<div class="toc">
<ul>
<li><a href="#section1">第一节</a></li>
<li><a href="#section2">第二节</a></li>
<li><a href="#section3">第三节</a></li>
</ul>
</div>
.toc {
border-left: 3px solid #3498db;
padding-left: 15px;
margin: 20px 0;
}
.toc ul {
list-style-type: none;
padding: 0;
}
.toc li {
margin: 8px 0;
}
.toc a {
text-decoration: none;
color: #2c3e50;
transition: color 0.3s;
}
.toc a:hover {
color: #3498db;
}
自动生成带编号的目录
通过 CSS 计数器实现自动编号:
body {
counter-reset: section;
}
.toc ol {
counter-reset: subsection;
list-style-type: none;
}
.toc ol li:before {
counter-increment: section;
content: counters(section, ".") " ";
}
固定侧边栏目录

当页面滚动时保持目录可见:
.toc {
position: fixed;
top: 20px;
left: 20px;
width: 250px;
max-height: 90vh;
overflow-y: auto;
}
响应式目录设计
适应不同屏幕尺寸:

@media (max-width: 768px) {
.toc {
position: static;
width: 100%;
max-height: none;
}
}
添加视觉层次
通过缩进显示目录层级:
.toc li.level1 { padding-left: 0; }
.toc li.level2 { padding-left: 20px; }
.toc li.level3 { padding-left: 40px; }
高亮当前浏览章节
使用 JavaScript 动态添加活动类:
.toc a.active {
color: #e74c3c;
font-weight: bold;
}
这些方法可以根据具体需求组合使用,创建出既美观又实用的网页目录结构。






