css:hover状态改变另一个元素样式的使用

情景1:

`
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css" media="screen">
        body{
            margin: 0;
            padding: 0;
        }
        .container .ul li{
            width: 100px;
            height: 20px;
            background: #f00;
            margin-bottom: 10px;
            list-style: none;
        }
        .container{
            border: 1px solid #000;
        }
        .container:hover ul.ul>li:nth-child(2){
            background: #000;
        }
    </style>
</head>
<body>
    <div class="container">
        <ul class="ul">
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </div>
</body>
</html>`

分析:当hover的元素和需要改变样式的元素是父子关系的时候,可以这么写(.container:hover ul.ul>li:nth-child(2))直接在hover后面加上空格,加上需要改变你的元素


情景2:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css" media="screen">
        body{
            margin: 0;
            padding: 0;
        }
        .wrap{
            width: 100px;
            height: 100px;
            background: #6c0;
        }
        .container .ul li{
            width: 100px;
            height: 20px;
            background: #f00;
            margin-bottom: 10px;
            list-style: none;
        }
        .container{
            border: 1px solid #000;
        }
        .container:hover ul.ul>li:nth-child(2){
            background: #000;
        }
        .contianer:hover div.wrap{
            background: #000;
        }
    </style>
</head>
<body>
    <div class="container">
        <ul class="ul">
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </div>
    <div class="wrap"></div>
</body>
</html>

分析:此时是hover container容器,改变wrap框的背景颜色,但发现container和wrap不是父子关系而是兄弟关系,这时候这样写(.contianer:hover div.wrap{background: #000;})不起效果。应该的写法是(.container:hover +.wrap{background:#f00;})

这里写图片描述

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值