如何检测用户的浏览器并应用特定的 CSS 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5621749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 00:12:31  来源:igfitidea点击:

How do I detect the user’s browser and apply a specific CSS file?

cssuser-agent

提问by Sourav

I need to detect the browser and apply the matched CSS file.

我需要检测浏览器并应用匹配的 CSS 文件。

I have created 3 css files: __ie.css, ff.css, opera.css. Now I need to detect the browser in order to include the good one.

我创建了 3 个 css 文件:__ie.css、ff.css、opera.css。现在我需要检测浏览器以包含好的浏览器。

I know this

我知道这个

<!--[if IE]>
     <link rel="stylesheet" href="css/ie.css" type="text/css"/>
<![endif]-->

But how do I do the same with Firefox and Opera/Chrome?

但是我如何对 Firefox 和 Opera/Chrome 做同样的事情?

采纳答案by derekerdmann

If you have to detect browsers just to apply CSS, then you might want to rethink your CSS before going to browser-specific stylesheets. All it takes is for one browser to mimic another's user agent string, or a new version to be released, and everything breaks. Use the current standards and validate your code (http://validator.w3.org/), and you'll have to worry about far fewer cross-browser issues. Even just using <!--[if IE]><![endif]-->without a version number could break the layout in later versions.

如果您必须检测浏览器才能应用 CSS,那么您可能需要在使用特定于浏览器的样式表之前重新考虑您的 CSS。只需要一个浏览器模仿另一个浏览器的用户代理字符串,或者发布一个新版本,一切都会中断。使用当前标准并验证您的代码 ( http://validator.w3.org/),您将不必担心跨浏览器问题。即使只是在<!--[if IE]><![endif]-->没有版本号的情况下使用也可能会破坏更高版本的布局。

That being said, if you want to style the page differently based on what CSS features are available, take a look at Modernizr. This way, you're only checking features, which won't be broken if a new version of the browser is released.

话虽如此,如果您想根据可用的 CSS 功能对页面进行不同的样式设置,请查看Modernizr。这样,您只检查功能,如果发布新版本的浏览器,这些功能不会被破坏。

If all else fails and you really need to detect the visitor's browser, try jquery.browser. It's built into jQuery, and is simple to use. http://api.jquery.com/jQuery.browser/.

如果所有其他方法都失败并且您确实需要检测访问者的浏览器,请尝试jquery.browser. 它内置于 jQuery 中,并且易于使用。http://api.jquery.com/jQuery.browser/

回答by cimmanon

The closest you can come with pure CSS is with feature queries. Instead of detecting the browser type/version, it allows you to check if a specific property/value combinations are supported by the browser.

与纯 CSS 最接近的是特性查询。它不是检测浏览器类型/版本,而是允许您检查浏览器是否支持特定的属性/值组合。

The following is an example of using the transform property for vertical centering. If the browser doesn't support transform, then we don't want to adjust its positioning:

以下是使用 transform 属性进行垂直居中的示例。如果浏览器不支持转换,那么我们不想调整它的定位:

@supports (transform: translateY(-50%)) {
    .foo {
        position: relative;
        top: 50%;
        transform: translateY(-50%);
    }
}

Browser support for Feature Queries

浏览器对特征查询的支持

回答by Spudley

If you need to browser detect for Firefox, Opera and Chrome, then you're doing something wrong. The same CSS should work in all of them.

如果您需要为 Firefox、Opera 和 Chrome 进行浏览器检测,那么您就做错了。相同的 CSS 应该适用于所有这些。

There are exceptions to this of course -- all the browsers have missing features and bugs which don't appear in the other browsers. An example would be text-overflow:ellipsiswhich isn't supported by Firefox.

当然,也有例外——所有浏览器都缺少其他浏览器中没有的功能和错误。一个例子text-overflow:ellipsis是 Firefox 不支持

However, if you're sticking to commonly used features, these cases are few and far between, and in general, you really shouldn't need to do browser detection these days, except for various versions of IE.

但是,如果您坚持使用常用功能,那么这些情况很少见,而且一般来说,这些天您真的不需要进行浏览器检测,除了各种版本的 IE。

If you're not sure whether the features you want to use are supported by most browsers, you can find out at CanIUse.comor Quirksmode.

如果您不确定大多数浏览器是否支持您要使用的功能,您可以在CanIUse.comQuirksmode 上找到。

If you're using seriously cutting-edge features, then yes, you will have problems with cross-browser support. But in this case it's generally better to do feature detection, using a product like Modernizr, rather than browser detection, since this will be a more reliable way of ensuring you cover all browsers and all versions, including future versions (which is an inherent weakeness of browser detection).

如果您正在使用非常先进的功能,那么是的,您将遇到跨浏览器支持的问题。但在这种情况下,通常最好使用Modernizr 之类的产品进行特征检测,而不是浏览器检测,因为这将是一种更可靠的方法,可确保您覆盖所有浏览器和所有版本,包括未来版本(这是一个固有的弱点浏览器检测)。

回答by Abdollah

Sometimes you can use prefixed properties that each browser apply their own properties based on their prefixes and ignore others. Following code fills a background by CSS3 gradient:

有时您可以使用前缀属性,每个浏览器根据其前缀应用自己的属性并忽略其他属性。以下代码通过 CSS3 渐变填充背景:

background-color: green;
background-image: url(my-img.png);
background-image: -webkit-linear-gradient(top right, #b51111, #eeeeee);
background-image: -moz-linear-gradient(top right, #b51111, #eeeeee);
background-image: -ms-linear-gradient(top right, #b51111, #eeeeee);
background-image: -o-linear-gradient(top right, #b51111, #eeeeee);
background-image: linear-gradient(top right, #b51111, #eeeeee);

In this code:

在这段代码中:

  • The -webkit- is for WebKit-based browsers (Chrome and Safari)
  • The -moz- is for Firefox
  • The -ms- is for Internet Explorer
  • The -o- is for Opera
  • -webkit- 用于基于 WebKit 的浏览器(Chrome 和 Safari)
  • -moz- 适用于 Firefox
  • -ms- 适用于 Internet Explorer
  • -o- 用于 Opera

But generally speaking, browser sniffing is not the best way, because it can easily fail in newer browsers. In that way, you have to get User Agent string of the browser and parse it. Then apply specific css rules for each browser based on its supported features. If User Agent string of the browser change in newer versions, you must modify your browser sniffing code. Imagine that you want to support multiple browsers and each of them may release some new versions in one year! You can query the browser that if it supports a given feature. e.g. HTML5 video:

但总的来说,浏览器嗅探并不是最好的方法,因为它在较新的浏览器中很容易失败。这样,您必须获取浏览器的用户代理字符串并解析它。然后根据其支持的功能为每个浏览器应用特定的 css 规则。如果浏览器的用户代理字符串在较新版本中发生变化,则必须修改浏览器嗅探代码。想象一下,您要支持多个浏览器,并且每个浏览器都可能在一年内发布一些新版本!您可以查询浏览器是否支持给定功能。例如 HTML5 视频:

if(!!document.createElement('video').canPlayType === true) {
// run some code that relies on HTML5 video
} else {
// do something else
}

There is a feature detection library named Modernizrthat is written based on JavaScript. You can download it and include it using in your html page. Also you must add 'no-js' class to your element. Modernizer runs all of its feature detection tests and and some classes to element; something like this:

有一个基于 JavaScript 编写的名为Modernizr的特征检测库。您可以下载它并将其包含在您的 html 页面中。此外,您必须向元素添加“no-js”类。Modernizer 运行其所有功能检测测试和一些元素类;像这样:

<html lang="en-gb" class=" js no-flexbox no-flexbox-legacy canvas canvastext 
webgl no-touch geolocation postmessage websqldatabase no-indexeddb
hashchange history draganddrop no-websockets rgba hsla multiplebgs
backgroundsize borderimage borderradius boxshadow textshadow opacity
cssanimations csscolumns cssgradients no-cssreflections csstransforms 
no-csstransforms3d csstransitions fontface generatedcontent video audio  
localstorage sessionstorage webworkers applicationcache svg inlinesvg 
smil svgclippaths">

So, you can apply CSS rules selectively. For instance, you want to apply an animated 3D transform in supporting browsers or display something in others. Consider the following code:

因此,您可以有选择地应用 CSS 规则。例如,您想在支持的浏览器中应用动画 3D 变换或在其他浏览器中显示某些内容。考虑以下代码:

#my-div:hover {
  transform: rotateY(90deg);
}

for default case and below for alternative:

对于默认情况和以下替代方案:

.no-csstransforms3d #my-div:hover {
  position: relative;
  right: 200px;
}

This is a good articledescribing the concept.

这是一篇描述这个概念的好文章

回答by Anup Bangale

I got a requirement of adding pure CSS to show thin scrollbars in my application which should apply for every browser, so I did it in this way. This code will detect the browser and sets the style to the scrollbars in entire application.

我需要添加纯 CSS 以在我的应用程序中显示细滚动条,这应该适用于每个浏览器,所以我这样做了。此代码将检测浏览器并将样式设置为整个应用程序中的滚动条。

// Scroll bar css settings in global css file like styles.css

/*IE*/
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
  html,
  body,
  div {
    scrollbar-face-color: #d1d8da;
    scrollbar-track-color: #dcd5d5;
    scrollbar-3dlight-color: #dcd5d5;
    scrollbar-darkshadow-color: #dcd5d5;
    scrollbar-arrow-color: #dcd5d5;
    -ms-overflow-style: -ms-autohiding-scrollbar; // this one will hide scroll-bars after sometime
    scrollbar-width: thin;
  }
}

/* for chrome */
@media screen and (-webkit-min-device-pixel-ratio: 0) {
  ::-webkit-scrollbar {
    width: 8px;
    height: 5px;
    border-radius: 10px;
  }
  ::-webkit-scrollbar-track {
    border-radius: 10px;
    background-color: #dcd5d5;
  }
  ::-webkit-scrollbar-thumb {
    border-radius: 10px;
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    background-color: #d1d8da;
  }
  ::-webkit-scrollbar-thumb:hover {
    background-color: #767979;
  }
}

/* for firefox */
@-moz-document url-prefix() {
  html,
  body,
  div {
    scrollbar-width: thin;
    scroll-behavior: smooth;
  }
}
<div style="height: 150px;width: 400px;overflow: auto;">
<ul style="list-style-type:circle;">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul> 
</div>

回答by easwee

There are no conditional comments for browsers other than IE.

IE 以外的浏览器没有条件注释。

But you can do it with javascript: http://www.quirksmode.org/js/detect.html

但是你可以用 javascript 来做:http: //www.quirksmode.org/js/detect.html

回答by artnikpro

Maybe I'm too late, but. The better solution is to use CSS/JS Browser Determiner(4kb minified). Disclaimer: This is a commercial productthat I sell.

也许我来得太晚了,但是。更好的解决方案是使用CSS/JS 浏览器确定器(4kb 缩小)。 免责声明:这是我出售的商业产品

To separate CSS and JS files, past this code to your <html>tag:

要分离 CSS 和 JS 文件,请将此代码传递到您的<html>标签:

<head><script src="js/cssjs-browser-determiner.min.js"></script>

<!-- Old Browsers -->
<script>
browser.is_old && document.writeln(
  '<link href="styles/old-browser.css" rel="stylesheet">'
);
</script>

This file will be only loaded for old browsers (by default, those that does not support CSS3 transition). If you want to separate files for each specific browser you can do the same but change browser.is_oldto browser.chromeor browser.webkitetc...

该文件将只为旧浏览器加载(默认情况下,不支持 CSS3 过渡的浏览器)。如果您想为每个特定浏览器分隔文件,您可以执行相同的操作,但更改browser.is_oldbrowser.chromebrowser.webkit等...

Then, write some CSS for specific browser inside old-browser.css (or any other CSS file):

然后,在 old-browser.css(或任何其他 CSS 文件)中为特定浏览器编写一些 CSS:

.opera9 .my-el { ... }
.firefox1_5 .my-el { ... }
.ie8- .el { ... } // IE8 or less
.ios .el { ... } // iPhone, iPad, iPod
etc...