如何仅用HTML、CSS或Bootstrap实现目标时间轴样式?
时间轴样式调整求助:年份定位与圆形背景图问题
我希望实现特定的时间轴样式,目前基于基础时间轴示例代码仅完成了初步效果。尝试将年份调整到时间轴旁的目标位置未成功,同时想为时间轴上的圆形节点设置背景图片,但目前只能实现纯色填充,请求解决这两个问题。
现有代码
CSS 代码
/* 时间轴主容器 */ .timeline { position: relative; max-width: 1200px; margin: 0 auto; } /* 时间轴竖线 */ .timeline::after { content: ' '; position: absolute; width: 6px; background-color: #ffc200; top: 0; bottom: 0; left: 50%; margin-left: -5px; } /* 内容容器 */ .contaiment { padding: 10px 40px; position: relative; background-color: inherit; width: 50%; } /* 时间轴圆形节点 */ .contaiment::after { content: ''; position: absolute; width: 25px; height: 25px; right: -11px; background-color: #ffc200; border: 4px solid #ffc200; top: 15px; border-radius: 50%; z-index: 1; } /* 左侧容器 */ .left { left: 0; } /* 右侧容器 */ .right { left: 50%; } /* 右侧容器箭头 */ .right::before { content: " "; height: 0; position: absolute; top: 22px; width: 0; z-index: 1; left: 30px; border: medium solid white; border-width: 10px 10px 10px 0; border-color: transparent white transparent transparent; } /* 右侧容器圆形节点位置修正 */ .right::after { left: -16px; } /* 内容卡片 */ .content { padding: 20px 30px; background-color: white; position: relative; border-radius: 6px; }
HTML 代码
<div class="timeline"> <div class="contaiment left"> <div class="content"> <p>2017</p> <p>Lorem ipsum..</p> </div> </div> <div class="contaiment right"> <div class="content"> <p>2017</p> <p>Lorem ipsum..</p> </div> </div> <div class="contaiment left"> <div class="content"> <p>2017</p> <p>Lorem ipsum..</p> </div> </div> </div>
解决方案
1. 年份定位到时间轴旁
将年份从内容卡片中移出,改为独立元素并通过绝对定位固定到时间轴两侧:
修改后的 HTML
<div class="timeline"> <div class="contaiment left"> <span class="year">2017</span> <div class="content"> <p>Lorem ipsum..</p> </div> </div> <div class="contaiment right"> <span class="year">2017</span> <div class="content"> <p>Lorem ipsum..</p> </div> </div> <div class="contaiment left"> <span class="year">2017</span> <div class="content"> <p>Lorem ipsum..</p> </div> </div> </div>
添加年份 CSS 样式
/* 年份基础样式 */ .year { position: absolute; top: 12px; z-index: 2; font-weight: bold; white-space: nowrap; } /* 左侧年份定位 */ .left .year { right: -60px; /* 可根据需求调整与时间轴的距离 */ } /* 右侧年份定位 */ .right .year { left: -60px; /* 可根据需求调整与时间轴的距离 */ }
2. 圆形节点设置背景图片
替换圆形节点的纯色背景为背景图片,同时保持边框样式:
.contaiment::after { content: ''; position: absolute; width: 25px; height: 25px; right: -11px; /* 替换为你的图片路径 */ background-image: url('你的图片地址'); background-size: cover; background-position: center; border: 4px solid #ffc200; top: 15px; border-radius: 50%; z-index: 1; }
注意:若图片尺寸适配不佳,可调整圆形的
width/height,或改用background-size: contain避免图片拉伸变形。
内容的提问来源于stack exchange,提问作者Hirdzan Rizki Rahman
相关产品推荐
相关产品推荐

