css中hover属性的使用技巧

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>
  • 15
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值