CSS3中,我们为了添加某种效果可以从一种样式转变到另一个的时候,无需使用Flash动画或JavaScript
CSS3 过渡是元素从一种样式逐渐改变为另一种的效果。
要实现这一点,必须规定两项内容:
- 指定要添加效果的CSS属性
- 指定效果的持续时间。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>css3 过渡</title> <style type="text/css"> * { margin: 0; padding: 0; } .example { width: 100px; height: 100px; background: red; transition: width 2s; /* 指定要添加效果的css属性为width持续时间为2s*/ -webkit-transition: width 2s; } .example:hover { width: 200px; } </style> </head> <body> <div class="example"></div> </body> </html>
要添加多个样式的变换效果,添加的属性由逗号分隔:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>css3 过渡</title> <style type="text/css"> * { margin: 0; padding: 0; } .example { width: 100px; height: 100px; background: red; transition: width 2s, height 2s, transform 2s; -webkit-transition: width 2s, height 2s, -webkit-transform 2s; } .example:hover { width: 200px; height: 200px; -webkit-transform: rotate(180deg); transform: rotate(180deg); } </style> </head> <body> <div class="example"></div> </body> </html>
下表列出了所有的过渡属性:
属性 | 描述 | CSS |
---|---|---|
transition | 简写属性,用于在一个属性中设置四个过渡属性。 | 3 |
transition-property | 规定应用过渡的 CSS 属性的名称。 | 3 |
transition-duration | 定义过渡效果花费的时间。默认是 0。 | 3 |
transition-timing-function | 规定过渡效果的时间曲线。默认是 "ease"。 | 3 |
transition-delay | 规定过渡效果何时开始。默认是 0。 | 3 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>css3 过渡</title> <style type="text/css"> * { margin: 0; padding: 0; } .example { width: 100px; height: 100px; background: red; transition-property: width; transition-duration: 1s; transition-timing-function: linear; transition-delay: 2s; /* Safari */ -webkit-transition-property: width; -webkit-transition-duration: s; -webkit-transition-timing-function: linear; -webkit-transition-delay: 2s; } .example:hover { width: 200px; } </style> </head> <body> <div class="example"></div> </body> </html>
与上面的例子相同的过渡效果,但是使用了简写的 transition 属性:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>css3 过渡</title> <style type="text/css"> * { margin: 0; padding: 0; } .example { width: 100px; height: 100px; background: red; transition:width 1s linear 2s; /* Safari */ -webkit-transition:width 1s linear 2s; } .example:hover { width: 200px; } </style> </head> <body> <div class="example"></div> </body> </html>