【问题标题】:Change H2 color when mouse hover in DIV鼠标悬停在 DIV 中时更改 H2 颜色
【发布时间】:2018-05-13 20:49:51
【问题描述】:

当鼠标悬停在特定 DIV 中时,我更改了 DIV 的背景。我正在使用 CSS 来做到这一点。

.home--student:hover {
    background-image: url("blahblah.jpg");
    color:white !important;
}

上面是我用于 DIV 的代码,但我使用的主题有一个 h2 类,它赋予 h2 橙色,!important 不会覆盖它。

还有其他方法可以做到这一点吗?无需编辑主题文件。我还希望鼠标离开 div 时颜色恢复为橙色,所以我不想更改 h2 类。

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    以比主题更具体的方式定位H2

    例子:

    如果主题有:

    h2 { background: orange; }
    

    用(考虑到 h2 存在于 div.someclass 容器中)覆盖它:

    div.someclass > h2 { background-color: red; }
    

    或者如果它没有任何父母:

    body > h2 { ... }
    

    或:

    h2.some-custom-class { ... }
    

    编辑:如果你想在鼠标悬停 div 时更改 H2 的颜色:

    div.home--student:hover > h2 { ... }
    

    或者如果 h2 不是 div 的直接子级,则:

    div.home--student:hover h2 { ... }
    

    【讨论】:

    • 我正在考虑这样做,但我需要在鼠标悬停在 div 中时触发它,如果我只是悬停在 h2 上就不会那么好
    • 编辑了答案以在鼠标悬停 div 时更改 h2 颜色
    • 谢谢!!我不知道你可以这样做
    【解决方案2】:

    这可能就是你想要的:

    .home--student:hover {
        background-image: url("blahblah.jpg");
    }
    
    .home--student:hover, .home--student:hover h2 {
        color:white !important;
    }
    

    .home--student:hover<div> 为目标,.home--student:hover h2<div> 内的任何<h2> 为目标!


    注意

    你确定你真的需要!important吗?除非您要覆盖的 CSS 使用 !important 本身,否则您实际上并不需要 !important

    在这种情况下,只需确保the specificity of your CSS 足够高!

    【讨论】:

    • 非常有用的解释和编写代码的简单方法,也感谢您的注意
    猜你喜欢
    • 2017-02-24
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 2018-11-23
    • 2011-08-24
    相关资源
    最近更新 更多