Search code examples
javascripthtmlcssmobile

how to change css file in html page using js if the user has a page width below a certain threshold


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">

Solution

  • 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.

    <!DOCTYPE html>
    <!--copied from https://www.w3schools.com/howto/howto_css_media_query_breakpoints.asp-->
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
    .example {
      padding: 20px;
      color: white;
    }
    /* Extra small devices (phones, 600px and down) */
    @media only screen and (max-width: 600px) {
      .example {background: red;}
    }
    
    /* Small devices (portrait tablets and large phones, 600px and up) */
    @media only screen and (min-width: 600px) {
      .example {background: green;}
    }
    
    /* Medium devices (landscape tablets, 768px and up) */
    @media only screen and (min-width: 768px) {
      .example {background: blue;}
    } 
    
    /* Large devices (laptops/desktops, 992px and up) */
    @media only screen and (min-width: 992px) {
      .example {background: orange;}
    } 
    
    /* Extra large devices (large laptops and desktops, 1200px and up) */
    @media only screen and (min-width: 1200px) {
      .example {background: pink;}
    }
    </style>
    </head>
    <body>
    
    <h2>Typical Breakpoints</h2>
    <p class="example">Resize the browser window to see how the background color of this paragraph changes on different screen sizes.</p>
    
    </body>
    </html>