媒体查询问题 - 防止覆盖 CSS 规则

Issue with media queries - Prevent override of CSS rules

最初我有我的基础 CSS 然后我添加了一个 640 媒体查询...

@media screen and (max-width:640px) {}

我对所有内容进行了编码以适应移动设备,一切都很好。刚才我添加了另一个媒体查询...

@media screen and (max-width:840px) {}

现在,我网站的移动部分正在使用第二个媒体查询的代码?我不知道 phone 的最大宽度有那么大。为什么 840 媒体查询会干扰我的移动媒体查询?

为了防止 CSS 被覆盖,使用下面的代码只为 640px840px 之间的宽度指定规则:

@media screen and (min-width: 640px) and (max-width:840px) { 
  /* CSS rules for width between 640px and 840px */
}

或者您可以重新排序代码:

@media screen and (max-width:840px) {} 

@media screen and (max-width:640px) {} /* This will override the above CSS rules */

查看此页面:MDN Media Queries 学习一些好的做法。

你可以用manoj说的。

这是来自 CSS tricks 的指南 - 希望对您有所帮助

/* Smartphones (portrait and landscape) ----------- */
    @media only screen 
    and (min-device-width : 320px) 
    and (max-device-width : 480px) {
    /* Styles */
    }

    /* Smartphones (landscape) ----------- */
    @media only screen 
    and (min-width : 321px) {
    /* Styles */
    }

    /* Smartphones (portrait) ----------- */
    @media only screen 
    and (max-width : 320px) {
    /* Styles */
    }

    /* iPads (portrait and landscape) ----------- */
    @media only screen 
    and (min-device-width : 768px) 
    and (max-device-width : 1024px) {
    /* Styles */
    }

    /* iPads (landscape) ----------- */
    @media only screen 
    and (min-device-width : 768px) 
    and (max-device-width : 1024px) 
    and (orientation : landscape) {
    /* Styles */
    }

    /* iPads (portrait) ----------- */
    @media only screen 
    and (min-device-width : 768px) 
    and (max-device-width : 1024px) 
    and (orientation : portrait) {
    /* Styles */
    }

    /* Desktops and laptops ----------- */
    @media only screen 
    and (min-width : 1224px) {
    /* Styles */
    }

    /* Large screens ----------- */
    @media only screen 
    and (min-width : 1824px) {
    /* Styles */
    }

    /* iPhone 4 ----------- */
    @media
    only screen and (-webkit-min-device-pixel-ratio : 1.5),
    only screen and (min-device-pixel-ratio : 1.5) {
    /* Styles */
    }

媒体查询在.css文件中的位置(顺序)起着重要的作用,它们在.css文件中按升序排列(从上到下),您只需要改变这个顺序如下:

将这个 @media screen and (max-width:840px) {} 媒体查询放在这个 @media screen and (max-width:640px) {} 上面,它会解决问题。

或者您可以使用以下 CSS:

@media screen and (min-width: 640px) and (max-width:840px) { 
  /* your code here */
}