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

时间:2015-08-29 05:40:21

标签: html css media-queries

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

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

我将所有内容编码为移动设备,一切都很好。一点前我添加了另一个媒体查询...

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

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

3 个答案:

答案 0 :(得分:4)

为了防止覆盖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了解一些良好做法。

答案 1 :(得分:2)

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

将此@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 */
}

答案 2 :(得分:1)

你可以使用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 */
    }
相关问题