cssmedia-queriescssom

Media queries: Overriding CSS rules vs defining screen specific CSS rules


I assume that, just like the media queries that are used in link tags, the media queries which we define in our CSS files are parsed/overwritten or omitted by the browser according to their media query rules (Actually I know that, although the CSS files requested by the link tags with unmatched media are anyway downloaded, they are not render blocking the browser). So, from the CSSOM build optimization stand point, isn't it better to separate the generic CSS rules that applies to all screen devices from the mobile specific CSS rules and encapsulate the mobile specific rules in a max-width media query? So that browser will parse less CSS to build CSSOM without the need of overwriting them for tablet, desktop etc. I wonder if that would affect the building of CSSOM performance or is it just overkill?


Solution

  • <link> tags with unmatched media queries are download with low priority so that they don't block page rendering, but are still downloaded in order to be available in case media properties change (for example by rotating a smartphone or by zooming out a desktop browser). There is an advantage in having separate stylesheets for different media types, but there is also a disadvantage in creating multiple HTTP requests.

    Media blocks inside a stylesheet are already downloaded and I would assume that they are compiled anyway, so it's not really the same as a media query in the tag. But if a certain set of rules is only relevant to a certain width and is always overriden in wider screens, it makes sense to tell the browser that by encapsulating it inside a media query. It's not just about the original page rendering but about any change to the window or to the DOM that requires a redraw - the less rules the browser would need to evaluate, the faster it would be.