CSS hover
:
CSS hover选择器用于在将鼠标移到元素上时选择它们。它不仅限于链接。我们几乎可以在每个
HTML 元素上使用它。要为未访问页面的链接设置样式,我们可以使用:
link 选择器。要为访问页面的链接设置样式,我们可以使用
:visited 选择器,为活动链接设置样式,可以使用
:active 选择器。
在CSS中引入。悬停可用于根据有效的Web设计程序中用户的偏好来突出显示网页。
悬停功能包括以下效果:
更改背景和字体的颜色。
修改图像的不透明度。
文本嵌入。
创建图像翻转效果。
交换图像。
注意:要使悬停有效,我们必须在CSS定义中的:link和:visited选择器之后声明它。
基本上,悬停效果会修改元素的属性值,以对指定的图像/文本或相应元素启用动画更改。悬停元素嵌入到网页中使它们具有交互性和功能。
通常,悬停功能与所有主要浏览器兼容。但是,在触摸设备上实现它将是一项艰巨的任务。观察到活动的悬停功能卡在了不支持的设备上。
语法
:hover {
css declarations;
}
让我们通过使用一些插图来理解它。
示例1:使用CSS更改悬停时的链接颜色
让我们看看颜色如何当我们将光标置于其上时,
链接的位置会更改。它将产生时尚的效果,并且在我们使用
CSS 时很容易实现。
<html>
<head>
<style>
body{
text-align:center;
}
a
{
color: red;
}
a:hover
{
color: green;
}
a:active
{
color: cyan;
}
</style>
</head>
<body>
<h1>Move your mouse on the below link to see the hover effect.</h1>
<a class = "link" href = https://www.Lidihuo.com/css-grid>CSS Grid</a>
</body>
</html>
<html>
<head>
<style>
body{
text-align:center;
}
p:hover, h1:hover, a:hover{
background-color: yellow;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<p>Welcome to the Lidihuo.</p>
<a href='https://www.Lidihuo.com/css-grid'>CSS Grid</a>
</body>
</html>
示例3-图像悬停在文本上的文字
此CSS代码在鼠标悬停期间在图像上显示文本。让我们看看鼠标悬停时的图像叠加效果。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{
text-align:center;
}
* {box-sizing: border-box;}
.container {
position: relative;
width: 50%;
max-width: 300px;
}
.image {
display: block;
width: 100%;
height: auto;
}
.overlay {
position: absolute;
bottom: 0;
background: rgba(0, 0, 0, 0.2);
width: 100%;
opacity:0;
transition: .9s ease;
font-size: 25px;
padding: 20px;
}
.container:hover .overlay {
opacity: 1.5;
}
</style>
</head>
<body>
<h1>Image Overlay Title Effect</h1>
<h2>Move your mouse over the image to see the effect.</h2>
<center>
<div class="container">
<img src="jtp.png" class="image">
<div class="overlay">Welcome to Lidihuo.com</div>
</div> </center>
</body>
</html>