过渡效果 ( transition )
CSS transitions 提供了一种在更改 CSS 属性时控制动画速度的方法。其可以让属性变化成为一个持续一段时间的过程,而不是立即生效的。
CSS transition 可以决定哪些属性发生动画效果(明确地列出这些属性),何时开始(设置 delay),持续多久(设置 duration)以及如何动画(定义 timing function)。
1)transition和animation的区别
- transition 必须要触发,一般使用 :hover
- transition 不需要设置关键帧
简单的过渡效果使用 transition,复杂的动画使用 animation
2)应用
速写:
transition : property duration timing delay ;
例:transition : margin-right 2s ease-in-out .5s ;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>过渡效果</title>
<style>
.box {
width: 300px;
height: 200px;
font-size: 0;
border: 1px solid red;
overflow: hidden;
/*边框过渡设置*/
transition-property: border;
transition-duration: 2s;
}
/*边框过渡效果*/
.box:hover{
/*当光标移到box上,边框粗细、颜色改变*/
border: 10px solid teal;
}
img {
width: 100%;
/*图片过渡设置*/
transition-property: transform;
transition-duration: 3s;
transition-timing-function: linear;
}
/*图片过渡效果*/
.box:hover > img{
/*当光标移到box上,图片放大2倍*/
transform: scale(2);
}
</style>
</head>
<body>
<div class="box">
<img src="./image/lianjia_03.png" alt="">
</div>
</body>
</html>
当光标移到box上,盒子边框粗细逐渐变为10px,颜色变为teal,图片放大2倍,当光标移开时,又慢慢恢复到原来的样子。
变形 ( transform )
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>变形</title>
<style>
body {
margin: 0;
}
.box {
width: 300px;
height: 300px;
text-align: center;
line-height: 300px;
background-color: pink;
transition: transform 2s linear;
transform-origin: center;
}
/*当光标移动到box上,box向左移动200px*/
.box:hover {
transform: translateX(-200px);
}
.cell {
height: 300px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="box">hello world</div>
<div class="cell"></div>
</body>
</html>