关键帧动画

CSS3 教程 · 第 6 章 · 8 次浏览

transition 只在状态变化时动一次,@keyframes 动画则可以定义多段、循环、自主控制的动画。

定义动画

用 @keyframes 定义关键帧,from/to 或百分比指定不同时间点的样式:

使用动画

animation: 名称 时长 曲线 延迟 次数 方向。常用写法:

  • animation: pulse 2s infinite 无限循环
  • animation: fadeIn 1s ease both,both 让动画前后应用第一/最后一帧
  • 可以多个动画逗号叠加

代码示例

@keyframes pulse {
    0%   { transform: scale(1); opacity: 1; }
    50%  { transform: scale(1.1); opacity: .7; }
    100% { transform: scale(1); opacity: 1; }
}

@keyframes slideIn {
    from { transform: translateX(-100%); }
    to   { transform: translateX(0); }
}

.badge {
    animation: pulse 1.5s infinite;
}
.banner {
    animation: slideIn .5s ease both;
}
📚 CSS 属性速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
写法 / 语法作用
color: #333;文字颜色
background: #fff;背景色 / 背景图
font-size: 16px;字号
font-family: Arial;字体
font-weight: bold;字重(加粗)
margin: 10px;外边距(上右下左)
padding: 10px;内边距
border: 1px solid #ccc;边框:粗细 样式 颜色
border-radius: 8px;圆角
width: 100%;宽度
height: 200px;高度
display: flex;弹性布局(现代布局主力)
display: none;隐藏元素
position: relative / absolute / fixed;定位方式
top / left / right / bottom定位偏移
text-align: center;文字水平对齐
line-height: 1.6;行高
overflow: hidden;内容溢出处理
box-shadow: 0 2px 8px rgba(0,0,0,.1);阴影
transition: all .3s;过渡动画
cursor: pointer;鼠标手型
z-index: 10;层叠顺序
max-width: 1200px; margin: 0 auto;容器居中(经典写法)
@media (max-width: 768px) {}响应式断点
:hover鼠标悬停状态