如何根据浏览器宽度动态调整 css 样式表? [英] How do I dynamically adjust css stylesheet based on browser width?

查看:101
本文介绍了如何根据浏览器宽度动态调整 css 样式表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在开发一款开源网络应用,供世界各地的艺术教师协同工作.我们需要一个不错的网站,它可以根据浏览器的活动宽度自行调整,例如 google.org 或 barackobama.com 做得很好.

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.

我们不希望我们的 CSS 根据浏览器类型或原始宽度而改变,而是希望它根据视口的当前宽度每毫秒调整一次——无论它是否是移动"设备或平板"机器或桌面"浏览器.

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.

奇怪的是,我使用 Google Apps Script 来托管我们的网络应用程序,所以看起来所有元视口标签都被删除了.

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?

推荐答案

您可以使用 CSS 媒体查询,如下所示:

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

或者 jQuery,像这样:

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());
    });
});

两者均来自:http://css-tricks.com/resolution-specific-stylesheets/

这篇关于如何根据浏览器宽度动态调整 css 样式表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆