hover属性用不同的书写方式,来改变不同关系的元素样式。
元素:hover 表示聚焦后改变自己
元素:hover 元素 表示聚焦后改变其子元素
元素:hover + 元素 表示聚焦后改变其指定的“亲兄弟”(条件是该兄弟元素与其相邻)元素
元素:hover ~ 元素 表示聚焦后改变其指定的兄弟元素,两个元素相不相邻都行。
示例:
.first:hover {color: white;}/* 聚焦我改变自己 */
.three:hover .three-son {font-size: 20px;}/* 聚焦我改变我的子元素 */
.two:hover+.three {color: white;}/* 聚焦我改变我相邻的兄弟元素 */
.first:hover~.four {font-weight: 900;color: palegreen;}/* 聚焦我改变不相邻的兄弟元素*/
效果图示:
完整代码如下:
<!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>
.all{
background-color: orchid;
width: 200px;
}
.all :nth-child(-n+3){
margin-bottom: 10px;
}
.first {color: yellow;}
.two {color: red;}
.three {color: black;}
.three-son {color: black;}
.four {color: green;}
.first:hover {color: white;}/* 聚焦我改变自己 */
.three:hover .three-son {font-size: 20px;}/* 聚焦我改变我的子元素 */
.two:hover+.three {color: white;}/* 聚焦我改变我相邻的兄弟元素 */
.first:hover~.four {font-weight: 900;color: palegreen;}/* 聚焦我改变不相邻的兄弟元素 */
</style>
</head>
<body>
<div class="all">
改变本身,改变不相邻(~):
<div class="first">我是黄字</div>
改变相邻(+):
<div class="two">我是红字</div>
改变子元素:
<div class="three">我是老黑
<div class="three-son">我是小黑</div>
</div>
<div class="four">我是绿字</div>
</div>
</body>
</html>