Change css file based on browser height

Can I change which CSS file loads depending on the height of the browser?

For example, if the browser is smaller than 600px, use index_sm.css, but use index_lg.css otherwise.

+5
source share
4 answers

In the tags, <head>put the following:

<script type="text/javascript">
    if (window.innerHeight <= 600) {
        loadcss('index_sm.css');
    } else {
        loadcss('index_lg.css');
    }

    function loadcss(file) {
        var el = document.createElement('link');
        el.setAttribute('rel', 'stylesheet');
        el.setAttribute('type', 'text/css');
        el.setAttribute('href', file);
        document.getElementsByTagName('head')[0].appendChild(el);
    }
</script>
+2
source

This is the best answer I could come up with, I finally found it by chance on a very useful site.

function adjustStyle(width) {
    width = parseInt(width);
    if (width < 701) {
        $("#size-stylesheet").attr("href", "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());
    });
});

Website: http://css-tricks.com/6206-resolution-specific-stylesheets/

jQuery changes the css browser on the fly, so if you change the size of your browser, css will change. It also works in all browsers.

+2
source

- ( , -).

0

You can use media queries, as Quentin said. But, I think you already have n css files and you want to select one of them on the fly. Just use something like this in your document.

<script language="text/javascript">
if (screen.width == 640) {
  document.write('<link rel="stylesheet" type="text/css" href="640.css">');
}
else if (screen.width == 800) {
  document.write('<link rel="stylesheet" type="text/css" href="800.css">');
}
</script>
0
source

All Articles