1

我正在进行自适应网站设计,并使用特定的 css 媒体查询来匹配较小的显示宽度。

对于我正在使用的小型显示器:

@media screen and (max-width: 34em) {}

对于更大的显示器,我正在使用:

@media screen and (min-width: 34em) {}

到目前为止,这工作得很好。但是,我注意到窗口有一定宽度,两个媒体查询的样式似乎混合在一起。(绝对不是没有应用查询的情况。)这肯定是一个边缘情况,但可能有人在那里用特定的窗口或屏幕宽度进行冲浪,并且看到一个看起来很奇怪的页面。因此,我想知道为什么会存在这个问题以及我能做些什么。我在 Mac 上的 Safari 和 Firefox 上都试过这个,都显示出相同的效果。

4

3 回答 3

4

However, I have notice that there is a certain width of the window where the styles from both media queries seem to be mixed together. (It definitely isn't the case that no query is applied.)

Correct; instead, both of them are being applied, and that's when the width of the viewport exactly equals 34 ems. What happens then is that the cascade applies as usual. See my answer to the following question for an explanation:

What are the rules for CSS media query overlap?

The easiest way to handle this for two ranges of screen sizes is to utilize the cascade, but differently from what you have: by writing your rules generally for one screen size, and only including a media query for the other screen size as shown in dwreck08's answer.

Otherwise, if you want exactly one rule to be applied at a time without relying on the cascade to override your styles, use either min-width or max-width only, and negate it in the other rule with the not keyword. As an example, you can have either this:

@media screen and (max-width: 34em) {}     /* Smaller screen sizes */
@media not screen and (max-width: 34em) {} /* Larger screen sizes */

Or this:

@media not screen and (min-width: 34em) {} /* Smaller screen sizes */
@media screen and (min-width: 34em) {}     /* Larger screen sizes */

The ordering does not matter because not makes these rules mutually exclusive — at least, in the browsers that understand the keyword, which as far as I know is all of them that support media queries anyway.

My answer to this question, which is a follow-up to the one linked above, offers another explanation:

How can I avoid media query overlap?

于 2013-06-18T21:12:04.077 回答
1

看起来您只需要两种可能的样式。因此,我认为您应该能够删除最大宽度查询并像往常一样设置它的样式以达到预期的结果。

  #divName {
  properties: here;
}

@media screen and (min-width: 34em) {
  #divName {
   properties: here;
   }
}
于 2013-06-18T20:29:57.727 回答
0

也许是因为您在 34em 处同时拥有最小宽度和最大宽度。因此,当屏幕大小正好是 34 em 时,两个媒体查询都处于活动状态。

您应该尝试将一侧的值更改一个 em,看看它是如何工作的。

@media screen and (max-width: 34em) {}
@media screen and (min-width: 35em) {}
于 2013-06-18T20:39:29.877 回答