如何用CSS实现圆形与虚线竖线对齐并弹跳时同步调整竖线高度?
解决方案
修改后的完整代码
CSS
.pin { display: flex; flex-direction: column; align-items: center; position: relative; margin: 30px; /* 仅用于方便观察,可按需调整 */ } .circle { color: #ffffff; background: #ff5500; width: 30px; height: 30px; border-radius: 50%; font-size: 25px; font-weight: bold; display: flex; align-items: center; justify-content: center; animation: bounceAndStretch 1s infinite ease-in-out; } @keyframes bounceAndStretch { 0% { transform: translateY(-10px); } 25% { transform: translateY(10px); } 50% { transform: translateY(-10px); } 75% { transform: translateY(10px); } 100% { transform: translateY(0); } } .vline { border-left: 1px dashed orangered; height: 50px; animation: stretchLine 1s infinite ease-in-out; } @keyframes stretchLine { 0% { height: 60px; /* 圆形上跳时,竖线拉长 */ } 25% { height: 40px; /* 圆形下跳时,竖线缩短 */ } 50% { height: 60px; } 75% { height: 40px; } 100% { height: 50px; /* 回到初始高度 */ } }
HTML
<div class="pin"> <div class="circle">!</div> <div class="vline"></div> </div>
关键改动说明
1. 实现圆形与竖线对齐
- 父容器
.pin改用flex布局,设置flex-direction: column让元素垂直排列,align-items: center确保所有元素水平居中,从根本上保证圆形和竖线在同一垂直线上。 - 圆形
.circle内部用flex布局实现感叹号的垂直+水平居中,避免文字偏移。
2. 同步弹跳与竖线高度变化
- 给圆形定义
bounceAndStretch动画,通过translateY属性实现上下弹跳,去掉了原代码中不必要的透明度变化(若需要闪烁效果可自行加回)。 - 给竖线定义
stretchLine动画,关键帧时间点与圆形完全同步:- 圆形向上移动时,竖线高度增加,模拟“跟随延伸”的效果;
- 圆形向下移动时,竖线高度减少,模拟“跟随收缩”的效果;
- 两个动画使用相同的时长和
ease-in-out缓动函数,确保动作完全同步。
内容的提问来源于stack exchange,提问作者Bilal
相关产品推荐
相关产品推荐

