css右导航栏制作
固定定位实现右导航栏
使用position: fixed将导航栏固定在视窗右侧,不受页面滚动影响。设置right: 0定位到右侧边缘,通过top和transform调整垂直居中。
.right-navbar {
position: fixed;
right: 0;
top: 50%;
transform: translateY(-50%);
width: 200px;
background: #f5f5f5;
padding: 20px;
box-shadow: -2px 0 5px rgba(0,0,0,0.1);
}
弹性布局控制内部元素
采用Flexbox布局管理导航项排列,flex-direction: column实现垂直堆叠。gap属性设置项目间距,align-items控制对齐方式。
.right-navbar {
display: flex;
flex-direction: column;
gap: 15px;
align-items: flex-end;
}
.nav-item {
padding: 10px 15px;
border-right: 3px solid transparent;
transition: all 0.3s ease;
}
.nav-item:hover {
border-right-color: #4CAF50;
}
响应式设计适配移动端
通过媒体查询在较小屏幕时调整导航栏样式。修改宽度、定位方式和显示形式以适应移动设备。
@media (max-width: 768px) {
.right-navbar {
width: 100%;
position: static;
flex-direction: row;
justify-content: center;
box-shadow: none;
padding: 10px 0;
}
.nav-item {
border-right: none;
border-bottom: 3px solid transparent;
}
}
滚动监听高亮当前章节
结合JavaScript实现滚动时自动高亮对应导航项。通过IntersectionObserverAPI检测元素可见性。
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const id = entry.target.getAttribute('id');
const navItem = document.querySelector(`.nav-item[href="#${id}"]`);
if (entry.isIntersecting) {
navItem.classList.add('active');
} else {
navItem.classList.remove('active');
}
});
}, { threshold: 0.5 });
document.querySelectorAll('section').forEach(section => {
observer.observe(section);
});
对应CSS样式:
.nav-item.active {
font-weight: bold;
color: #4CAF50;
border-right-color: #4CAF50;
}






