要实现一个从中心向四周扩展(缩放)的CSS动画,可以使用CSS的transform
属性结合scale()
函数,并通过transform-origin
将变换原点设置在元素的中心。以下是一个完整的示例,展示如何实现这一效果:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>CSS 动画示例</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<div class="animated-box"></div>
</div>
</body>
</html>
styles.css
)/* 设置页面背景和居中容器 */
body, html {
height: 100%;
margin: 0;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
background-color: #f0f0f0;
}
/* 定义动画元素 */
.animated-box {
width: 100px;
height: 100px;
background-color: #3498db;
border-radius: 8px;
/* 设置变换原点为中心 */
transform-origin: center center;
/* 初始状态:缩放比例为0 */
transform: scale(0);
/* 添加过渡效果 */
transition: transform 1s ease-out;
}
/* 触发动画的状态(例如,悬停时) */
.animated-box:hover {
transform: scale(2); /* 放大到原始大小的2倍 */
}
.container
包含一个需要动画效果的元素 .animated-box
。flex
布局将 .animated-box
居中显示在页面中。transform-origin: center center;
将变换的原点设置在元素的中心,这样在缩放时,元素会从中心向四周扩展。transform: scale(0);
将元素缩放为0,即不可见。transition: transform 1s ease-out;
使变换过程有1秒的平滑过渡效果。.animated-box
上时,通过 :hover
伪类将 transform
属性更改为 scale(2)
,使元素放大到原始大小的2倍。你可以根据需要调整缩放比例或触发动画的事件(例如点击、加载等)。@keyframes
动画:
@keyframes expandFromCenter { from { transform: scale(0); opacity: 0; } to { transform: scale(1); opacity: 1; } } .animated-box { /* 其他样式保持不变 */ animation: expandFromCenter 1s ease-out forwards; }
这样,.animated-box
在页面加载时会自动从中心扩展到原始大小,并保持最终状态。.animated-box
的尺寸和动画参数,以适应不同的屏幕尺寸和设备。领取专属 10元无门槛券
手把手带您无忧上云