CSS 媒体查询 - 多与少

标签 css media-queries

假设 1 个 css 文件和 3 个 @media 格式,例如:

@media (min-width:1280px)
@media (min-width:640px) and (max-width:1279px)
@media (max-width:639px)

使用每种 @media 格式一次和在其中塞入所有适当的 CSS 规则之间是否存在显着的性能差异,例如:

@media (min-width:1280px) {
  /* all css for this format */
}

@media (min-width:640px) and (max-width:1279px) {
  /* all css for this format */
}

@media (max-width:639px) {
  /* all css for this format */
}

VS

根据需要使用尽可能多的 @media 声明(大约与 CSS 规则/部分一样多)...例如:

div.some-class-name {
  /* styles */
}

@media (min-width:1280px) {
  div.some-class-name {
    /* styles for this format */
  }
}

@media (min-width:640px) and (max-width:1279px) {
  div.some-class-name {
    /* styles for this format */
  }
}
@media (max-width:639px) {
  div.some-class-name {
    /* styles for this format */
  }
}

我个人更喜欢版本 2(尽管可能不是那么夸张),因为跟踪每个 @media 查询的特定样式对要容易得多。

感谢反馈!

最佳答案

我不是这方面的专家,但我找到了一篇不错的文章来解决这个问题:

https://helloanselm.com/2014/web-performance-one-or-thousand-media-queries/

It doesn’t matter if you use one big or multiple media-queries in your code assuming your values are mostly the same. It shouldn’t matter if your values are different for each(!) of your hundreds of media-queries but could affect performance (found no way to track this down). The only thing I could add here is that using many inline media queries often is that they’re increasing the size of your CSS (unless your gzipping it) and that affects performance as it’s loaded blocking.

对我来说很有意义。我个人喜欢对元素样式进行分组,而不是对媒体查询进行分组(您问题中的版本 2)。在我看来,CSS 的目标是设计元素的样式,而根据屏幕尺寸设计元素的样式是次要目标。

关于CSS 媒体查询 - 多与少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26620110/

相关文章:

html - 如何将边框半径设置为表格边框?

html - div 内的元素但在 View 中不可滚动

html - 媒体查询 - 使图像响应

printing - 将页脚与打印的 HTML 页面的底部对齐?

使用媒体查询后 HTML 被禁用

html - 仅在特定元素内引用 CSS 类

css - Plone 发送一个指向已缓存但为空的 ploneCustom.css 的链接

html - z-index 过渡延迟不起作用?

html - Bootstrap "Navbar"css 类在我的 html 页面上不起作用

css - @import 样式在媒体查询中不起作用