简体   繁体   English

CSS 媒体查询不适用于任何浏览器

[英]CSS media queries doesn't work on any browser

I looked on every thread and I tried every possible solution to no avail.我查看了每个线程,并尝试了所有可能的解决方案,但均无济于事。 It just doesn't work on any browser...它在任何浏览器上都不起作用......

HTML HTML

<html>
<head>
    <link type="text/css" rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1"/>
</head>
<body>
    <div class="bg">
    </div>
    
</body>

CSS: CSS:

    @media only screen and (max-width: 1200){
    .bg{
        background-color: green;
    }
}

*{
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}

.bg{
    background-color: black;
    height: 100vh;   
}

Any suggestions?有什么建议么?

You have 2 problems that are preventing it from working:您有 2 个问题阻止它工作:

  1. You need to specify the unit (eg px) in the (max-width: 1200px) - otherwise it doesn't recognise the breakpoint您需要在(max-width: 1200px)指定单位(例如 px) - 否则无法识别断点
  2. You need to include the media query after the default css for .bg .您需要在.bg的默认 css之后包含媒体查询 Because you are including the media query before .bg{background-color: black;...} , this is overriding the CSS rule in the media query that set is to green.因为您在.bg{background-color: black;...}之前包含媒体查询,所以这会覆盖设置为绿色的媒体查询中的 CSS 规则。

See this in a working snippet (Click "Expand Snippet" to see it in fullscreen with a black background):在工作片段中查看此内容(单击“扩展片段”以全屏黑色背景查看):

 * { box-sizing: border-box; padding: 0; margin: 0; }.bg { background-color: black; height: 100vh; } @media only screen and (max-width: 1200px) {.bg { background-color: green; } }
 <div class="bg"> </div>

You should be using min-width in your media queries and apply them using mobile first approach.您应该在媒体查询中使用min-width并使用移动优先方法应用它们。 It means first you apply default styles which will apply to any screen if there are no media queries.这意味着首先您应用默认的 styles 如果没有媒体查询,它将应用于任何屏幕。 Then you reset styles for larger screen sizes.然后你重置 styles 以获得更大的屏幕尺寸。 The default styles then only apply to smaller screens.默认的 styles 仅适用于较小的屏幕。

Example:例子:

/* Default style */
.sample-class {
  color: #ff0000;
}

/* Reset style for screen sizes that are 768px or higher */
@media screen and (min-width: 768px) {
  .sample-class {
    color: #777777;
  }
}

Do make sure that you are implementing styles in the order above.请确保您按上述顺序实施 styles。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM