如何实现圆形从中心向左右两侧同时展开的动画效果?
实现圆形从中心向左右两侧同时展开的动画效果
原代码仅修改width属性,由于元素默认左对齐,展开方向为从左至右,无法实现中心对称的展开效果。以下是两种可行的解决方案:
方案一:使用transform缩放(推荐)
利用transform: scaleX()实现以元素中心为原点的水平缩放,是最简洁的实现方式:
.logo { width: 100px; height: 100px; border-radius: 50%; /* 使用百分比适配任意尺寸 */ background: red; transition: transform 2s ease; margin: 0 auto; /* 可选:让元素居中显示,便于观察效果 */ } .logo:hover { transform: scaleX(3); /* X轴缩放3倍,对应原宽度从100px扩展到300px的比例 */ }
<div class="logo"></div>
scaleX()变换默认以元素中心为原点,因此缩放时会自然向左右两侧同时扩展,同时保持圆形的高度和圆角比例不变。
方案二:调整宽度与位置偏移
若需要精确控制宽度的具体数值,可通过相对定位调整元素位置,抵消宽度增加带来的偏移:
.logo { width: 100px; height: 100px; border-radius: 50%; background: red; transition: all 2s ease; position: relative; left: 0; margin: 0 auto; /* 可选:居中显示 */ } .logo:hover { width: 300px; left: -100px; /* 宽度增量为200px,向左偏移一半(100px)实现中心展开 */ }
<div class="logo"></div>
当宽度从100px增加到300px时,通过left: -100px让元素向左偏移宽度增量的一半,从而实现视觉上从中心向两侧展开的效果。
内容的提问来源于stack exchange,提问作者Marcos Carvalho
相关产品推荐
相关产品推荐

