<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
body{
height: 100vh;
background-color: #515151;
display: flex;
align-items: center;
justify-content: center;
}
button{
width: 250px;
outline: 0;
height: 50px;
border: white solid 2px;
background-color: #515151;
color: white;
position: relative;
}
button::before{
content: '';/* 忘了 */
position: absolute;
top: -2px;
left: -2px;
background-color: brown;
width: 0;
height: 0;
z-index: 0;
transition: all .5s;
}
button:hover::before{
/* transition: .5s; */
width: calc(100% + 4px);
height: calc(100% + 4px);
}
button p{
background-color: #515151;/* 一定要设置 */
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
}
button::after{
content: '';/* 忘了 */
position: absolute;
right: -2px;
bottom: -2px;
background-color: brown;
width: 0;
height: 0;
z-index: 0;
transition: all .5s;
}
button:hover::after{
/* transition: .5s; */ /* transition如果加在这里只有鼠标移上去有效,移走无效 */
width: calc(100% + 4px);
height: calc(100% + 4px);
}
</style>
</head>
<body>
<button>
<p>Button</p>
</button>
</body>
</html>
注意点:
1.transition应该放在::before中,而不是:hover::before中,要不然动画效果只有鼠标移上去时有效,移走无效。
2.::before一定要加content
3.要给p设置background-color,否则遮盖不住::before
4.p为块级元素,但里面不放盒子
5.calc要注意加空格
6.width的辖域是内容,left是距离border向里的一条边,padding会挤大盒子。如下图