Defining CSS media queries within selectors

前端 未结 3 1655
我在风中等你
我在风中等你 2021-02-01 16:48

Are there any issues (performance is my primary concern) if instead of defining css selectors within media queries (example 1), you define media queries within css selectors (ex

相关标签:
3条回答
  • 2021-02-01 17:15

    The issue is it doesn't work! Things may have changed over the years. I tried putting media queries inside the selectors, at least Firefox complains its an invalid property name.

    Here's what MDN says:

    The @media at-rule may be placed at the top level of your code or nested inside any other conditional group at-rule.

    It can only be nested inside another conditional group at-rule.

    0 讨论(0)
  • 2021-02-01 17:19

    Short answer, no. There are no performance issues in defining media queries within CSS selectors.

    But let's dive in...

    As described in Anselm Hannemann great article Web Performance: One or Thousands of Media Queries there is no performance loss from adding the media queries in the manner you are.

    As long as the same set of media queries are being used in each selector there is no major performance hit other than your CSS file might be a bit larger.

    .foo {
      @media (min-width: 600px) { ... }
      @media (min-width: 1000px) { ... }
      @media (min-width: 1500px) { ... }
    }
    
    .bar {
      @media (min-width: 600px) { ... }
      @media (min-width: 1000px) { ... }
      @media (min-width: 1500px) { ... }
    }
    

    However, it does matter how many different media queries you use. Different being different min-widths, max-widths and so on.

    0 讨论(0)
  • 2021-02-01 17:33

    There shouldn't be a performance difference looking at the way browsers handle media queries. Browser engines do serialize and strip out duplicated media-queries so they only need to evaluate each media query once. Also they cache the queries so that they can re-use it later on. It doesn’t matter if you use one big or multiple media-queries in your code assuming your values are mostly the same.


    Some of the possibilities when there can be performance issues

    • You use multiple media queries with different values and the browser window is re-sized. As the browser window is re-sized, multiple media queries can be a big overhead on the cpu.
    • When the CSS selectors are too complex. A complex CSS selector is much performance hindering than multiple media queries. So having multiple media queries inside complex selectors can cause performance issues
    0 讨论(0)
提交回复
热议问题