使用CSS识别浏览器和操作系统?

JWe*_*hal 4 css css3

我知道为特定的浏览器或操作系统编写特定的CSS代码并不正确,但在我正在构建的网站中,某些元素在特定的浏览器中无法很好地呈现.例如,IE8中不支持某些元素,或者在小型iPhone显示屏中看起来很奇怪.

因此我的问题是 - 使用CSS是否可以识别用户浏览器和操作系统并允许我编写不同的显示选项?

你好.

小智 8

可悲的是,我不相信每个系统只有纯css才有可能.

但是,您可以使用css和js的组合来查看系统.

见这里:http://rafael.adm.br/css_browser_selector/

  • 这实际上是一个非常糟糕的解决方案 UA嗅探非常不可靠.此外,未启用JavaScript的用户将无法获得正确的样式. (3认同)
  • 这是一个非常糟糕的解决方案,我没有看到它是如何以任何方式最干净的方式,如果你真的想使用JS至少使用像[Modernizr]这样的真实库(http://www.modernizr.com/) (2认同)

Myl*_*ray 8

您无法使用CSS嗅探操作系统或浏览器,但您可以使用@media查询来定位不同的屏幕尺寸,例如:

@media screen and (max-width: 1000px) { ... }
Run Code Online (Sandbox Code Playgroud)

以上是小型台式机和笔记本电脑屏幕.

@media screen and (max-width: 700px) { ... }
Run Code Online (Sandbox Code Playgroud)

以上是适用于iPad和非常小的台式机/笔记本电脑屏幕.

@media screen and (max-device-width: 480px) { ... }
Run Code Online (Sandbox Code Playgroud)

以上是iPhone 3GS和移动设备.

然而,新的iPhone 4与史蒂夫乔布斯的所有歌唱全舞"视网膜"显示意味着它的像素比率为2-1意味着1像素实际上出现在浏览器2x2像素使其分辨率(960x640 - 意味着它将触发iPad布局而不是移动设备布局)因此这需要另外的媒体查询(仅限webkit支持):

@media screen and (-webkit-min-device-pixel-ratio: 2) { ... }
Run Code Online (Sandbox Code Playgroud)

要定位不同的浏览器,您需要使用HTML if语句:

<!--[if IE]>
According to the conditional comment this is Internet Explorer
<![endif]-->
<!--[if IE 5]>
According to the conditional comment this is Internet Explorer 5
<![endif]-->
<!--[if IE 5.0]>
According to the conditional comment this is Internet Explorer 5.0
<![endif]-->
<!--[if IE 5.5]>
According to the conditional comment this is Internet Explorer 5.5
<![endif]-->
<!--[if IE 6]>
According to the conditional comment this is Internet Explorer 6
<![endif]-->
<!--[if IE 7]>
According to the conditional comment this is Internet Explorer 7
<![endif]-->
<!--[if gte IE 5]>
According to the conditional comment this is Internet Explorer 5 and up
<![endif]-->
<!--[if lt IE 6]>
According to the conditional comment this is Internet Explorer lower than 6
<![endif]-->
<!--[if lte IE 5.5]>
According to the conditional comment this is Internet Explorer lower or equal to 5.5
<![endif]-->
<!--[if gt IE 6]>
According to the conditional comment this is Internet Explorer greater than 6<br />
<![endif]-->
Run Code Online (Sandbox Code Playgroud)

然后只需在这些条件中链接CSS样式表