当父母盘旋时,孩子会改变

时间:2013-06-23 16:32:29

标签: html css sass

我正在尝试让父元素悬停时更改子元素。我也希望父母的属性也能改变。我试图让#action的背景颜色发生变化,ah1的颜色会在action悬停时发生变化。这可能吗?

这是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 个答案:

答案 0 :(得分: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 :(得分: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 中的&amp; 是指父元素,换句话说是 #action 本身。

我喜欢这种方法,因为一切都在一个样式声明中自包含,并且重复性较低。

就像说:“......当这个元素悬停时,将这些样式应用于它,并将这些样式应用于a和h1”。

关于标记@zachstames的一个小评论:a(锚元素)是内联内容元素,而h1(1级标题)是块元素。根据{{​​3}},内联元素不应包含块元素,只能包含数据。

希望它有所帮助。

干杯!

答案 2 :(得分:0)

这是你想要的? DEMO

你能够做到这一点:

#action:hover {
    background: yellow;
}

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

如您所见,我重复使用伪类#action:hover。我在说:

“当操作悬停时,在操作悬停时更改背景 AND ,更改a元素的背景和字体颜色。”

希望我帮助过。

好, 莱昂纳多