简体   繁体   中英

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

We're developing an open-source web app for arts teachers across the world to work together. We need a nice website that simply adjusts itself based on the active width of the browser, like google.org or barackobama.com does so well.

We can detect the browser, the OS, etc. but don't want to use any of that info. We just want four or five different stylesheets that are triggered when the browser width is adjusted.

So, for example, when you visit the app on a browser using a DESKTOP computer, you see the full app when the browser is full screen. Then, as the browser reduces its width the site immediately and dynamically changes its format to allow for universal compatibility.

We don't want our CSS to change based on browser type or original width, but instead want it to adjust ever millisecond based on the current width of the viewport -- regardless of whether or not it is a "mobile" device or a "tablet" machine or a "desktop" browser.

Curiously, I'm using Google Apps Script to host our web app, so it looks like any meta viewport tags are removed.

How can we introduce four or five different stylesheets based on the width of the current viewing browser window?

You can either use CSS media queries, like so:

<link rel="stylesheet" media="screen and (min-device-width: 700px)" href="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", "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/

css media queries is the way to go

<link rel='stylesheet' media='screen and (max-width: 700px)' href='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 (min-width: 901px)' href='css/wide.css' />

使用CSS媒体查询执行此操作

You can do with CSS.

<link rel='stylesheet' media='screen and (max-width: 480px)' href='css/mobile.css' />
<link rel='stylesheet' media='screen and (min-width: 481px)' href='css/pc.css' />

For more code & detail

Click Here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM