I want to change the css file depending on if the user is on mobile or on desktop. I couldnt find anything that actually works so i just restorted to using the js below to redirect the user to a diff html page with a diff css sheet. But i find this super inefficient. Does anyone know how I can make the css stylesheet change depending on the screen width property in the page?
<script type="text/javascript">
<!--
if (screen.width <= 699) {
document.location = "m_index.html";
}
//-->
</script>
<!-- main css -->
<link rel="stylesheet" href="master.css">
<!-- CSS with media query -->
<link rel="stylesheet"
media="screen and (max-width: 360px)"
href="small-screen.css">
<link rel="stylesheet"
media="screen and (min-width: 360px) and (max-width: 550px)"
href="large-screen.css">
2
Answers
Good idea to have responsive design, but that’s a weird way of doing it. Unless there’s a really good reason why you’re using JS for this, you can do it all in CSS, check this out for example: https://www.w3schools.com/howto/howto_css_media_query_breakpoints.asp
Open the above snippet in fullscreen and resize your window to see the demonstration.
See the MDN page for more detailed documentation.
You can achieve dynamic CSS loading based on screen width without resorting to JavaScript redirection.
But if you want, I add some sample code below.