How do I dynamically adjust css stylesheet based on browser width?

You can either use CSS media queries, like so:

<link rel="stylesheet" media="screen and (min-device-width: 700px)" href="https://stackoverflow.com/questions/11962837/css/narrow.css" />
<link rel="stylesheet" media="screen and (min-width: 701px) and (max-width: 900px)" href="css/medium.css" />
<link rel="stylesheet" media="screen and (max-device-width: 901px)" href="css/wide.css" />

Or jQuery, like so:

function adjustStyle(width) {
    width = parseInt(width);
    if (width < 701) {
        $("#size-stylesheet").attr("href", "https://stackoverflow.com/questions/11962837/css/narrow.css");
    } else if ((width >= 701) && (width < 900)) {
        $("#size-stylesheet").attr("href", "css/medium.css");
    } else {
       $("#size-stylesheet").attr("href", "css/wide.css"); 
    }
}

$(function() {
    adjustStyle($(this).width());
    $(window).resize(function() {
        adjustStyle($(this).width());
    });
});

Both found from: http://css-tricks.com/resolution-specific-stylesheets/

Leave a Comment