Is there any advantage or improvement to us using the media attribute in the link tag? If so?, then I don't need to use the @media rule in my CSS, using the media attribute will be enough to set the breakpoints for my web page, right?
Is there any advantage or improvement to us using the media attribute in the link tag? If so?, then I don't need to use the @media rule in my CSS, using the media attribute will be enough to set the breakpoints for my web page, right?
It can be handy for light/dark mode.
<link rel="stylesheet" href="light.css" media="(prefers-color-scheme: light)">
<link rel="stylesheet" href="dark.css" media="(prefers-color-scheme: dark)">
Example:
html, body {
background: #EEE;
}
@media (prefers-color-scheme: dark) {
html, body {
background: #444;
}
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.3.2/styles/default.min.css">
<link rel="stylesheet" href="https://unpkg.com/highlight.js@10.3.2/styles/github-gist.css" media="(prefers-color-scheme: light)">
<link rel="stylesheet" href="https://unpkg.com/highlight.js@10.3.2/styles/monokai-sublime.css" media="(prefers-color-scheme: dark)">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.3.2/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<pre class="hljs"><code class="language-javascript">function some(javacript) {
console.log(javascript);
}</code></pre>
This would also work
<link rel="stylesheet" href="light.css">
<link rel="stylesheet" href="dark.css" media="(prefers-color-scheme: dark)">
Defaults to light.css but overrides with dark.css if the user prefers dark
The browser downloads all CSS resources, regardless of the media attribute.
<link href="style.css" rel="stylesheet">
<link href="justForFrint.css" rel="stylesheet" media="print">
<link href="deviceSizeDepending.css" rel="stylesheet" media="(min-width: 40em)">
The difference is that if the media-query of the media attribute is evaluated to false then that .css file and his content will not be render-blocking.
Therefore, it is recommended to use the media attribute in the <link> tag since it guarantees a better user experience.
Here you can read a Google article about this issue https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-blocking-css
Some tools that will help you to automate the separation of your css code in different files according to your media-querys
Webpack https://www.npmjs.com/package/media-query-plugin https://www.npmjs.com/package/media-query-splitting-plugin
PostCSS https://www.npmjs.com/package/postcss-extract-media-query