Next.js Discord

Discord Forum

Seperate css files for web and mobile

Answered
Virginia's Warbler posted this in #help-forum
Open in Discord
Virginia's WarblerOP
Is there a way to only download the mobile css when the client is mobile, and download only the web css file when the client is a computer?
Answered by James4u
<link rel="stylesheet" href="desktop.css" media="(min-width: 768px)">
<link rel="stylesheet" href="mobile.css" media="(max-width: 767px)">
View full answer

6 Replies

ofc! @Virginia's Warbler
<link rel="stylesheet" href="desktop.css" media="(min-width: 768px)">
<link rel="stylesheet" href="mobile.css" media="(max-width: 767px)">
Answer
Media Queries are the simplest way to apply styles based on viewport size but do not prevent file downloads.
<script>
    if (window.innerWidth < 768) {
        // Load mobile CSS
        var link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = "mobile.css";
        document.head.appendChild(link);
    } else {
        // Load desktop CSS
        var link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = "desktop.css";
        document.head.appendChild(link);
    }
</script>
You can use JavaScript to detect the user agent or screen size and then dynamically load the appropriate CSS file. Using this method you only download CSS file depending on device size
Virginia's WarblerOP
thank you