【问题标题】:background-color not overwriting fully defined background property背景颜色不覆盖完全定义的背景属性
【发布时间】:2018-01-16 11:37:10
【问题描述】:

我正在制作一个包含三个元素的工具栏菜单,除了用作图标的不同背景图像外,它们应该具有相同的样式。

HTML:

<div id="menu-handheld">
    <a href="page.php?stuff=things" id="menu-handheld-tab-start">Start</a>
    <a href="page.php?stuff=things" id="menu-handheld-tab-trends">Trends</a>
    <a href="page.php?stuff=things" id="menu-handheld-tab-recent">Recent</a>
</div>

CSS:

#menu-handheld {
    position: fixed;
    width: 100%;
    height: 3.8rem;
    bottom: 0;
    z-index: 100;
}

#menu-handheld-tab-start { background: rgb(0, 51, 51) no-repeat 50% 0.5rem/2rem url(img/icons/start.svg) }
#menu-handheld-tab-trends { background: rgb(0, 51, 51) no-repeat 50% 0.5rem/2rem url(img/icons/trends.svg) }
#menu-handheld-tab-recent { background: rgb(0, 51, 51) no-repeat 50% 0.5rem/2rem url(img/icons/recent.svg) }

[id|=menu-handheld-tab], [id|=menu-handheld-tab]:visited { /* common CSS */
    display: block;
    float: left;
    box-sizing: border-box;
    width: 33.33333%;
    height: 100%;
    padding-top: 2.5rem;
    color: rgb(102, 153, 153);
    font-size: 1rem;
    font-family: treme-extra-light;
    text-decoration: none;
    text-align: center;
    transition: background 0.3s ease;
}

[id|=menu-handheld-tab]:active, [id|=menu-handheld-tab]:hover {
    background-color: rgb(102, 153, 153); /* this does not work */
    color: rgb(0, 51, 51); /* this works fine */
}

正如我在代码中评论的那样,:hover/:active 过渡在文本颜色上效果很好,但在背景颜色上根本不行。我相信这是我分别为每个元素使用的完全写出的背景属性的问题,因为当我尝试在通用 CSS 中定义背景属性并且仅在单独的选择器中使用背景图像时遇到了同样的问题。

我在这里做错了什么?为什么 background-color 或 background-anything 无法覆盖背景属性?我意识到我可以通过定义另一组三个 #menu-handheld-tab-stuff {} 选择器并写出新的完整背景定义来解决我的问题,但这不是解决方案。

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    颜色声明生效,因为没有要覆盖的现有颜色声明。

    background-color 声明不生效,因为 ID 选择器比属性选择器和伪类组合更具体。这是因为属性选择器始终不如 ID 选择器 even when that attribute selector is specific to the id attribute 特定。因此,每个包含 ID 选择器的规则都会保留其背景简写声明,包括其颜色值。

    通常情况下,解决这个问题会涉及到特异性黑客甚至使用!important,但在这种特定情况下,您应该能够将#menu-handheld 添加到您的选择器(并且,可选地,将属性选择器替换为更简单的a 类型选择器,因为#menu-handheld 没有其他孩子):

    #menu-handheld a:active, #menu-handheld a:hover {
        background-color: rgb(102, 153, 153);
        color: rgb(0, 51, 51);
    }
    

    (当你这样做时,为了保持一致性,我建议对前面的规则做同样的事情。)

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 1970-01-01
      • 2013-02-09
      • 2011-05-06
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多