如何修改现有CSS实现一侧图片一侧文字的垂直时间轴布局
解决方案
首先调整DOM结构,每个时间节点同时包含文字区和图片区,再通过CSS控制奇偶项的排布规则,修改后的代码如下:
示例HTML结构
<div class="entries"> <!-- 奇数项:文字在左,图片在右 --> <div class="entry"> <div class="content"> <h3 class="title">时间节点1</h3> <div class="body"> <p>这里是文字内容说明</p> </div> </div> <div class="img-box"> <img src="你的图片地址" alt="图片说明"> </div> </div> <!-- 偶数项:图片在左,文字在右 --> <div class="entry"> <div class="content"> <h3 class="title">时间节点2</h3> <div class="body"> <p>这里是文字内容说明</p> </div> </div> <div class="img-box"> <img src="你的图片地址" alt="图片说明"> </div> </div> </div>
修改后的CSS代码
/* 全局背景可根据需要自行调整 */ body { background-color: #1d1d1d; margin: 0; padding: 40px 0; } /* 中间时间轴竖线 */ body:before { content: ''; position: fixed; top: 0; left: 50%; bottom: 0; transform: translateX(-50%); width: 4px; background-color: #00ffff; } body .entries { width: calc(100% - 80px); max-width: 1200px; margin: auto; position: relative; z-index: 0; } /* 时间节点项设为弹性布局,占满整行 */ body .entries .entry { width: 100%; display: flex; justify-content: space-between; align-items: center; clear: both; margin-bottom: 60px; } /* 文字内容区宽度 */ body .entries .entry .content { width: calc(50% - 60px); position: relative; } /* 时间轴圆点,统一放在靠近中间线的一侧 */ body .entries .entry .content .title { font-size: 40px; position: relative; color: #ffffff; margin: 0 0 16px 0; } body .entries .entry .content .title:before { content: ''; position: absolute; width: 8px; height: 8px; border: 4px solid #00ffff; background-color: #1d1d1d; border-radius: 100%; top: 50%; transform: translateY(-50%); z-index: 1000; } body .entries .entry .content .title.big:before { width: 24px; height: 24px; } body .entries .entry .content .body { color: #ffffff; } body .entries .entry .content .body p { line-height: 1.4em; margin: 0; } /* 图片区宽度和样式 */ body .entries .entry .img-box { width: calc(50% - 60px); border-radius: 8px; overflow: hidden; line-height: 0; } body .entries .entry .img-box img { width: 100%; height: auto; } /* 奇数项:文字在左,圆点在内容区右侧 */ body .entries .entry:nth-child(odd) .content { text-align: right; order: 1; } body .entries .entry:nth-child(odd) .content .title:before { right: -70px; } body .entries .entry:nth-child(odd) .content .title.big:before { transform: translate(8px, -50%); } body .entries .entry:nth-child(odd) .img-box { order: 2; } /* 偶数项:文字在右,圆点在内容区左侧 */ body .entries .entry:nth-child(even) .content { text-align: left; order: 2; } body .entries .entry:nth-child(even) .content .title:before { left: -70px; } body .entries .entry:nth-child(even) .content .title.big:before { transform: translate(-8px, -50%); } body .entries .entry:nth-child(even) .img-box { order: 1; }
如果需要调整图文间距、圆点位置或者图片圆角等样式,直接修改对应参数即可。
内容的提问来源于stack exchange,提问作者lostjom
相关产品推荐
相关产品推荐

