打印媒体通用 (*) 规则在页脚元素上被覆盖

Print media universal (*) rule gets overridden on footer element

我一直在寻找问题的答案,但找不到其他人解决我的问题,所以我决定求助于堆栈溢出。

我正在为@media print 添加 CSS 规则,偶然发现了一个我无法理解的问题。我正在尝试使用 * 选择器将 background-color: white 应用于所有元素,但某些元素忽略了该规则并继续使用先前定义的颜色,覆盖了打印媒体规则。

这是可以重现问题的最简单的 CSS 文件:

footer {
    background-color: lightblue;
}

@media print {
    * {
        background-color: white;
    }
}

在我的 HTML 中,我有简单的页脚标签,没有任何 类 或 ID。

...
<footer>
    Footer content here
</footer>
...

我已经检查了 HTML 和 CSS 两者的有效性,所以它不应该是语法错误

如果我使用 Chrome 开发人员工具选项 模拟 CSS 媒体:打印 或使用 背景颜色打印预览并检查图像,页脚元素保留其浅蓝色。

如果我使用 Developer 工具检查元素,它显示 @media 打印规则已被覆盖:

背景颜色:白色;

我不明白为什么上面的页脚规则会覆盖 * 规则。据我所知,这两个规则具有相同的特殊性,所以最后一个应该被应用。但事实并非如此。如果我在媒体查询下编辑规则以明确声明该规则也应应用于页脚元素,它就会起作用:

*, footer {
    background-color: white;
}

但对我来说这似乎很奇怪,因为我认为 * 已经包含页脚元素。我当然可以只使用 CSS 和规则中指定的页脚,但我仍然很想知道 为什么 仅星号是不够的。

问题出在你的范围内

/* global scope */
footer {
    background-color: lightblue;
}
/* media-print scope */
@media print {
    * {
        background-color: white;
    }
}

由于您在全局范围内为 footer 定义了 background-color 并且 footer > *(具有更高的优先级,因为它更具体)它会覆盖您的全局背景颜色。


尝试以下方法修复它没有测试):

@media screen {
  footer {
    background-color: lightblue;
  }
}

@media print {
  * {
    background-color: white;
  }
}

尽管您的代码是正确的,但为了安全起见,我宁愿这样做 background-color: transparent(不过我认为打印机实际上不会打印白色......)。

footer {
  background-color: lightblue;
}

@media print {
  * {
    background-color: transparent; 
    /* Try emulating using this: 'background-color: transparent !important;', seems chrome emulator isn't respecting this without the !important rule. */
  }
}

我测试了你的代码,这似乎是开发工具模拟器的问题。当我模拟打印时,页脚仍然具有背景颜色。但是当我在网络浏览器中实际按下 "print" 时,背景如您所料是白色的。

看看 HTML5Boilerplate 的印刷品 CSS: https://github.com/h5bp/html5boilerplate.com/blob/master/src/css/_print.css

当您使用媒体查询时,它就像一个 if 语句,如果列出的条件适用,它就会包含该块中的样式。然而,它们并没有因为它们在媒体查询中而被赋予更高的特异性。 * 选择器的特异性总是低于页脚,无论它写在哪里。

这个 CSS Tricks, has probably the most comprehensive breakdown of CSS specificity. If you look under "Important Notes" you'll see the specificity of the * is 0,0,0,0 and the footer is 0,0,0,1. You can also check out this, crimsondesigns.com/blog/…(陷阱 #4)讨论了媒体查询的特异性问题。