在實際工作中,簡單利用css3的屬性可以讓頁面更生動,如下面的例子:
“瞭解詳情”的hover效果比單純的顏色變換效果更生動。而實現的方式就是簡單的利用了css3transition屬性。
頁面代碼結構如下:
<div class="box">
<a href="#">
<span>瞭解詳情</span>
<em></em>
</a>
</div>
原理
- 定位一個 初始width爲0的em元素,hover的時候再將 width設置爲容器的width.
- 再利用transiton對width變化的過程設置過度效果
css如下:
.box a {
position: relative;
z-index: 0;
display: inline-block;
width: 158px;
height: 38px;
line-height: 38px;
text-align: center;
color: #fff;
border: 1px solid #fff;
border-radius: 20px;
}
.box a em {
position: absolute;
z-index: -1;
top: 0px;
left: 0px;
display: inline-block;
width: 0;
height: 100%;
background-color: #fff;
border-radius: 20px;
transition: width .3s ease;
}
.box a:hover span {
color: #00aeff;
}
.box a:hover em {
width: 100%;
}
利用僞元素可以讓代碼更簡潔,語義化,代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/common.css"/>
<style>
.box {
height: 500px;
background-color: #4FAEE0;
}
.box a {
position: relative;
z-index: 0;
display: inline-block;
width: 158px;
height: 38px;
line-height: 38px;
text-align: center;
color: #fff;
border: 1px solid #fff;
border-radius: 20px;
}
.box a:after {
content: '';
position: absolute;
z-index: -1;
top: 0px;
left: 0px;
display: inline-block;
width: 0;
height: 100%;
background-color: #fff;
border-radius: 20px;
-moz-transition: width .3s ease;
-webkit-transition: width .3s ease;
-o-transition: width .3s ease;
transition: width .3s ease;
}
.box a:hover {
color: #00aeff;
}
.box a:hover:after {
width: 100%;
}
</style>
</head>
<body>
<div class="box">
<a href="#">瞭解詳情</a>
</div>
</body>
</html>
參考
- https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions
- https://developer.mozilla.org/en-US/docs/Web/CSS/transition
(完)