简体   繁体   English

为什么 CSS3 媒体查询 @media(max-width) 不起作用

[英]Why CSS3 media query @media(max-width) is not working

I am trying to apply some responsive design into the website.我正在尝试将一些响应式设计应用到网站中。 I do not understand why I have a problem when I apply the following media query.我不明白为什么我在应用以下媒体查询时会遇到问题。 Thank you for your help.谢谢您的帮助。 A part of HTML (index.html) HTML (index.html) 的一部分

<meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content ='ie-edge'>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.1/css/all.css" integrity="sha384-xxzQGERXS00kBmZW/6qxqJPyxW3UR0BPsL4c8ILaIWXva5kFi7TxkIIaMiKtqV1Q" crossorigin="anonymous">
    <link rel ='stylesheet' href='css/style.css'>
    <link rel='stylesheet' media='screen and (max-width: 768px)' href ='css/widescreen.css'>
    <link rel='stylesheet' media='screen and (min-width: 1100px)' href ='css/mobile.css'> 

CSS part in which media query is not working.媒体查询不起作用的 CSS 部分。 (mobile.css) (mobile.css)

/*Smartphones */
@media(max-width: 500px){
  #navbar {
    flex-direction: column;
    align-items: center;
  }
}

You need to add display:flex;您需要添加display:flex; inside #navbar在#navbar里面

@media(max-width: 500px){
  #navbar {
    display:flex; /*new*/
    flex-direction: column;
    align-items: center;
  }
}

First, the styles of "mobile.css" file will never be applied because you specified in the meta tag the expression: media='screen and (min-width: 1100px)' which tells the browser to apply the styles for devices with a screen's width >= 1100px, so below that, the "mobile.css" styles will not be applied.首先,“mobile.css”文件的 styles 将永远不会被应用,因为您在元标记中指定了表达式: media='screen and (min-width: 1100px)' ,它告诉浏览器将 styles 应用于具有屏幕宽度 >= 1100px,因此低于此值,将不会应用“mobile.css”styles。

Second, in case of a screen width >= 1100px, the mobile styles will not be applied because you added another media query with different rule @media(max-width: 500px) which tells the browser to apply the style if the screen's width is below 500px, while we are in a screen's width >= 1100px, it will never work...其次,如果屏幕宽度 >= 1100px,移动端 styles 将不会被应用,因为您添加了另一个具有不同规则@media(max-width: 500px)媒体查询,它告诉浏览器在屏幕宽度为低于 500 像素,当我们处于屏幕宽度 >= 1100 像素时,它永远不会工作......

To resolve your problem, just keep one expression rule to apply the styles of mobile.css file for smaller screens' width ( <= 500px ) like:要解决您的问题,只需保留一个表达式规则来应用 mobile.css 文件的 styles 以用于较小的屏幕宽度(<= 500px),例如:

<link rel='stylesheet' media='screen and (max-width: 500px)' href ='css/mobile.css'> 

And then, remove the duplicated media query rule in "mobile.css":然后,删除“mobile.css”中重复的媒体查询规则:

#navbar {
   flex-direction: column;
   align-items: center;
   display: flex;
}

Useful links:有用的链接:

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

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