How to Conditionally Load External CSS Based on Media Query in HTML?

If you want to load different CSS files based on some media queries, then you can do so by adding the media attribute on the HTML <link> element (which has great browser support). You can use it in the following way:

<link rel="stylesheet" href="path/to/styles.css" media="..." />

Here, the media attribute could contain any valid CSS media query. Setting this means that:

  • The user-agent is able to pick the best stylesheet for the device the web page is being viewed on (depending on the media query condition);
  • The CSS file is only loaded when the media query (defined in the media attribute) matches.

This can help you optimize the delivery of stylesheets (that might not immediately be needed on initial page load), which can be especially good for improving page speed and web core vital metrics.

For example, to load a stylesheet only when the condition "only screen and (min-width: 1440px)" matches, you can do the following:

<link
    rel="stylesheet"
    href="path/to/styles.css"
    media="only screen and (min-width: 1440px)"
/>

It is also possible to specify multiple media queries for a single stylesheet by separating each condition by a comma (,):

<link
    rel="stylesheet"
    href="path/to/styles.css"
    media="only screen and (width: 1024px), orientation: landscape"
/>

This would load this stylesheet if either "only screen and (width: 1024px)" or "orientation: landscape" matches. This is similar to how you would use media queries in CSS.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.