父元素悬浮时子元素改变

3
我正在尝试在父元素悬停时更改子元素。我还希望更改该父元素的一个属性。当悬停在action上时,我正在尝试更改#action的背景颜色和ah1的颜色。这可能吗?
以下是HTML代码:
<section id="action" class="general">
    <div class="container">
        <a href="#"><h1>This text</h1></a>
    </div>
</section>

以下是CSS代码。CSS使用SASS构建,因此结构如此。

#action {
    background-color: $bgLight;
    border-top: 1px solid #252525;
    -webkit-transition: all 0.2s ease-out;
    -moz-transition: all 0.2s ease-out;
    -ms-transition: all 0.2s ease-out;
    -o-transition: all 0.2s ease-out;
    transition: all 0.2s ease-out;

    a {
        text-decoration: none;

        h1 {
            margin: 0;
            color: $colorLight;
            font-weight: 300;
            text-align: center;
        }
    }
}

#action:hover a {
    background-color: #76A7D1;
    color: $colorDark;
}
3个回答

4

试试这个:

#action {
    background-color: $bgLight;
    border-top: 1px solid #252525;
    -webkit-transition: all 0.2s ease-out;
    -moz-transition: all 0.2s ease-out;
    -ms-transition: all 0.2s ease-out;
    -o-transition: all 0.2s ease-out;
    transition: all 0.2s ease-out;

    a {
        text-decoration: none;

        h1 {
            margin: 0;
            color: $colorLight;
            font-weight: 300;
            text-align: center;
        }
    }
}

#action:hover{
    background-color: #76A7D1;
    a{
       h1{
          color: $colorDark;
       }
     }
}

1

你可以按照 @Alessandro Minoccheri 的建议做相同的事情,但以更简洁的方式,这是我特别喜欢的:

#action {
    background-color: $bgLight;
    border-top: 1px solid #252525;
    -webkit-transition: all 0.2s ease-out;
    -moz-transition: all 0.2s ease-out;
    -ms-transition: all 0.2s ease-out;
    -o-transition: all 0.2s ease-out;
    transition: all 0.2s ease-out;

    a {
        text-decoration: none;

        h1 {
            margin: 0;
            color: $colorLight;
            font-weight: 300;
            text-align: center;
        }
    }
    &:hover{
        background-color: #76A7D1;
        a{
           h1{
              color: $colorDark;
           }
         }
    }

}
#action 中的 & 指的是父元素,也就是指 #action 本身。
我喜欢这种方法,因为所有样式声明都可以自包含在一个样式声明中,而且不会重复。
就像是说:“...当悬停在此元素上时,将应用这些样式到它,以及这些样式到a和h1。”
关于你的标记@zachstames的一个小注释:a(锚元素)是内联内容元素,而h1(一级标题)是块级元素。根据W3C规范,内联元素不应包含块级元素,只能包含数据。
希望有所帮助。
干杯!

0

这是你想要的吗?演示

你能够做到这个:

#action:hover {
    background: yellow;
}

#action:hover a {
    background-color: #76A7D1;
    color: white;
}

正如您所看到的,我重复使用了伪类#action:hover。我的意思是:

“当鼠标悬停在动作上时,更改其背景当鼠标悬停在动作上时,更改a元素的背景和字体颜色”。

希望我能帮到您。

祝好, 莱昂纳多


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接