Best Way To Place Media Queries [closed]

人盡茶涼 提交于 2021-02-05 08:27:09

问题


What is the best way to place media queries in HTML?

  1. In same CSS file like:

    .my-text {
      font-size: 30px;
    }
    
    @media only screen and (max-width : 768px) {
       .my-text {
         font-size: 24px;
        }
    }
    
    .my-img {
      width: 100%;
    }
    
    @media only screen and (max-width : 768px) {
       .my-img {
         width: 80%;
        }
    }
    
    {more styles...}
    
    @media only screen and (max-width : 768px) {
       {more styles...}
    }
    
  2. Or in same CSS but like:

    .my-text {
      font-size: 30px;
    }
    
    .my-img {
      width: 100%;
    }
    
    {more code....}
    
    @media only screen and (max-width : 768px) {
       .my-text {
         font-size: 24px;
        }
    
       .my-img {
         width: 80%;
        }
    
        {more code...}
    }
    
  3. Or should I use different stylesheets in HTML head tag using media query like:

    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" media="screen and (max-width: 768px)" href="small.css">
    

I'm learning web designing but I'm a bit confused which will work fine..


回答1:


The shortest answer is: it depends what you're trying to achieve.

The first option is the worst in terms of file size and readability because of doubling every @media rule makes all the rules longer and hard to effectively debug.

The second option (one CSS file with all media-specific rules grouped under one @media block per media type) is the best when there are rules which overlaps each other in terms of adding something to values coming from the other @media block. In this case this would be more SEO-friendly and economical (by means of number of requests) than downloading several separate CSS files to any matched @media.

The third option is the most effective when @media classifiers don't overlap with each other at all (because it results in a smaller file to download per page load, and only one CSS file is loaded at a time. This would be the best way to go if you have some CSS files for different layouts per device, while only one is needed per device resolution - i.e. one for horizontal resolutions below 320, one for 320-720, one for 720 upwards and one specifically for printing.




回答2:


The 2nd option would be the best practice as I have seen good designers use the 2nd strategy to implement media queries. First, write all your styles, then at the end, use media queries on whatever element needed.



来源:https://stackoverflow.com/questions/44222514/best-way-to-place-media-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!