在 CSS3 中,实现鼠标悬停效果主要使用 :hover 伪类。下面从基础到常见效果给你系统讲一下。
:hover 用法<button class="btn">按钮</button>
.btn {
background: #3498db;
color: #fff;
padding: 10px 20px;
border: none;
}
.btn:hover {
background: #2ecc71;
}
✅ 鼠标放上去时,背景颜色改变。
.box {
width: 200px;
height: 100px;
border: 2px solid #333;
}
.box:hover {
background: #f0f0f0;
color: red;
border-color: orange;
}
.box {
width: 200px;
height: 200px;
background: #3498db;
transition: all 0.3s ease;
}
.box:hover {
background: #e74c3c;
transform: scale(1.1);
}
✅ 平滑放大 + 变色
.box:hover {
transform: rotate(5deg);
}
.box:hover {
transform: translateY(-10px);
}
.img-box img {
width: 300px;
transition: transform 0.4s;
}
.img-box img:hover {
transform: scale(1.2);
}
<div class="img-box">
<img src="img.jpg">
<div class="mask">文字</div>
</div>
.img-box {
position: relative;
width: 300px;
}
.mask {
position: absolute;
inset: 0;
background: rgba(0,0,0,0.5);
color: #fff;
opacity: 0;
transition: 0.3s;
}
.img-box:hover .mask {
opacity: 1;
}
.menu:hover .submenu {
display: block;
}
.submenu {
display: none;
}
.btn::after {
content: "➡";
opacity: 0;
transition: 0.3s;
}
.btn:hover::after {
opacity: 1;
margin-left: 5px;
}
@keyframes shake {
0% { transform: translateX(0); }
50% { transform: translateX(5px); }
100% { transform: translateX(0); }
}
.box:hover {
animation: shake 0.3s;
}
| 场景 | 实现方式 |
|---|---|
| 按钮悬停 | background + transition |
| 图片放大 | transform: scale |
| 内容展示 | opacity / display |
| 悬浮浮动 | translateY |
| 动态效果 | animation |
✅ :hover 只在 鼠标设备 生效
✅ 移动端通常靠点击触发
✅ 性能建议:
transform / opacitywidth/height如果你有具体效果(比如轮播、卡片、菜单、按钮)或 想做的 UI 样式,可以直接发给 URL 或截图,我可以帮你写完整 CSS。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。