css制作目录
CSS 制作目录的方法
使用 CSS 可以创建一个美观且功能性的目录(TOC),以下是几种常见方法:
使用无序列表和样式
通过 <ul> 和 <li> 标签创建目录结构,并用 CSS 美化:
<div class="toc">
<ul>
<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>
</div>
.toc ul {
list-style-type: none;
padding-left: 0;
}
.toc li {
margin-bottom: 8px;
}
.toc a {
text-decoration: none;
color: #333;
padding: 4px 8px;
border-left: 3px solid #3498db;
}
.toc a:hover {
background-color: #f0f0f0;
}
自动生成目录
结合 JavaScript 可以动态生成目录,CSS 负责样式:
// 假设页面有 h2 标题
const headings = document.querySelectorAll('h2');
const toc = document.querySelector('.toc ul');
headings.forEach(heading => {
const li = document.createElement('li');
const a = document.createElement('a');
a.textContent = heading.textContent;
a.href = `#${heading.id}`;
li.appendChild(a);
toc.appendChild(li);
});
多级嵌套目录

对于多级标题(如 h2、h3),可以使用嵌套列表:
.toc ul ul {
margin-left: 20px;
border-left: 1px solid #ddd;
}
.toc ul ul li {
margin-bottom: 4px;
}
固定位置目录
使目录在滚动时保持可见:

.toc {
position: fixed;
top: 20px;
right: 20px;
width: 200px;
max-height: 80vh;
overflow-y: auto;
}
响应式设计
在小屏幕上隐藏或调整目录:
@media (max-width: 768px) {
.toc {
display: none;
}
}
添加图标或编号
使用 CSS 伪元素增强视觉效果:
.toc li::before {
content: "•";
color: #3498db;
margin-right: 8px;
}
这些方法可以根据具体需求组合使用,创建出符合项目风格的目录。






