效果演示
Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./01-色块滑动.css">
<title>01-色块滑动</title>
</head>
<body>
<a href="#">Hover Me</a>
</body>
</html>
body {
height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
a {
text-decoration: none;
color: black;
font-family: fans-serif;
font-size: 40px;
font-weight: bold;
border: 2px solid black;
padding: 40px 80px;
position: relative;
overflow: hidden;
}
a:before {
content: "若冰说CSS";
font-size: 20px;
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%;
background-color: black;
transform: translate(-100%);
transition: all 1s;
z-index: -1;
}
a:hover:before {
transform: translateX(0);
}
a:hover {
color: white;
}
实现思路拆分
① 基本结构
<a href="#">Hover Me</a>
② 布局
body {
/* 居中 */
height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
③ 设置色块样式
a {
/* 去除下划线 */
text-decoration: none;
/* 设置颜色 */
color: black;
/* 设置字体 */
font-family: fans-serif;
font-size: 40px;
font-weight: bold;
/* 设置边框 */
border: 2px solid black;
/* 内边距 */
padding: 40px 80px;
/* 定位 */
position: relative;
}
④ 设置悬停样式
a:before {
/* 内容 */
content: "若冰说CSS";
/* 文字大小 */
font-size: 20px;
/* 绝对定位 */
position: absolute;
/* 大小铺满 */
left: 0;
top: 0;
height: 100%;
width: 100%;
/* 背景色 */
background-color: black;
/* 变化样式 */
transform: translate(-100%);
transition: all 1s;
z-index: -1;
}
⑤ 隐藏悬停样式
a {
/* 隐藏 */
overflow: hidden;
}
⑥ 取消悬停恢复样式
a:hover:before {
/* 取消悬停后样式 */
transform: translateX(0);
}
a:hover {
/* 颜色 */
color: white;
}