📜  如何检测设备并交换 CSS 文件?

📅  最后修改于: 2021-08-30 13:09:04             🧑  作者: Mango

创建网页时,最重要的是前端的用户体验,尤其是设计部分或 CSS。为了获得流畅的体验,前端开发人员需要使网页具有响应性。由于“一刀切”,单一设计不适用于所有设备。这就是引入“媒体查询”的原因。在根据屏幕宽度、高度、位/像素等设置网站特定部分的样式时,媒体查询非常有用。
但是,如果要编写很多媒体查询,或者如果我们必须针对不同设备完全更改网页的样式,有时编写媒体查询可能会令人困惑。因此,我们可以针对不同的屏幕尺寸使用不同的 CSS 文件。

这可以通过在 HTML 文件的 部分添加媒体查询来完成。

媒体查询可以像这样添加到 CSS 的链接部分,如下所示

可以使用的媒体类型

all (default) Used for all media type devices
print    Used for printers
screen Used for computer screens, tablets, smart-phones etc.
speech Used for screen readers that “reads” the page out loud

一些使网页响应的常用媒体功能

max-width Sets a maximum width till which CSS properties will be followed
min-width Sets a minimum width till which CSS properties will be followed
orientation Can be set to portrait/landscape

注意:在将 CSS 链接到 HTML 时,可以使用媒体查询的所有功能。

index.html

    
        
            GFG
  
            
            
  
            
            
            
  
        
        
        
            GeeksForGeeks
        
        
    


master.css
// master.css
  
body {
    display: flex;
    align-items: center;
    font-family: sans-serif;
}


small-screen.css
// small-screen.css
  
body {
    color: rgb(29, 176, 5);
    background-color: white;
}


large-screen.css
// large-screen.css
  
body {
    color: rgb(67, 164, 55);
    background-color: black;
}


CSS文件:

  • 1.master.css文件

    主文件

    // master.css
      
    body {
        display: flex;
        align-items: center;
        font-family: sans-serif;
    }
    
  • 2.small-screen.css文件

    小屏幕.css

    // small-screen.css
      
    body {
        color: rgb(29, 176, 5);
        background-color: white;
    }
    
  • 3.大屏幕.css文件

    大屏幕.css

    // large-screen.css
      
    body {
        color: rgb(67, 164, 55);
        background-color: black;
    }
    

输出:

当屏幕宽度小于 360px 时

当屏幕宽度大于 360px 小于 550px 时

当屏幕宽度大于 550px 时