css制作时间轴
时间轴的基本结构
使用HTML构建时间轴的基础结构,通常采用无序列表<ul>嵌套列表项<li>,每个列表项包含时间节点内容和时间标记:
<ul class="timeline">
<li>
<div class="content">
<h3>2023年事件</h3>
<p>事件描述文本</p>
</div>
<div class="time">2023</div>
</li>
<!-- 更多列表项 -->
</ul>
垂直时间轴样式
通过CSS实现垂直排列的时间轴,核心样式包括:
.timeline {
position: relative;
padding: 20px 0;
}
.timeline::before {
content: '';
position: absolute;
left: 50%;
width: 2px;
background: #3498db;
height: 100%;
}
.timeline li {
position: relative;
margin-bottom: 50px;
}
.timeline .content {
width: 40%;
padding: 20px;
background: #f9f9f9;
border-radius: 8px;
}
.timeline .time {
position: absolute;
left: 50%;
transform: translateX(-50%);
background: #3498db;
color: white;
padding: 5px 15px;
border-radius: 20px;
}
交替布局实现
使时间节点左右交替显示的改进方案:
.timeline li:nth-child(odd) .content {
margin-left: 60%;
}
.timeline li:nth-child(even) .content {
margin-right: 60%;
}
响应式处理
针对移动设备的适配调整:
@media (max-width: 768px) {
.timeline::before {
left: 30px;
}
.timeline .content {
width: calc(100% - 90px);
margin-left: 70px !important;
}
.timeline .time {
left: 30px;
transform: none;
}
}
动画效果增强
为时间轴添加交互动画:
.timeline li {
opacity: 0;
transition: all 0.5s ease;
}
.timeline li.show {
opacity: 1;
}
配合JavaScript实现滚动触发:
document.addEventListener('DOMContentLoaded', () => {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('show');
}
});
}, {threshold: 0.1});
document.querySelectorAll('.timeline li').forEach(li => {
observer.observe(li);
});
});
高级视觉样式
添加图标和阴影效果提升视觉层次:
.timeline li::after {
content: '';
position: absolute;
left: 50%;
top: 30px;
transform: translateX(-50%);
width: 20px;
height: 20px;
background: #fff;
border: 4px solid #3498db;
border-radius: 50%;
}
.timeline .content {
box-shadow: 0 3px 10px rgba(0,0,0,0.1);
transition: transform 0.3s;
}
.timeline .content:hover {
transform: translateY(-5px);
}






