简体   繁体   中英

CSS check for Chrome, IE, Firefox

I've noticed a small alignment issue in the three major browsers when rendering my web site. As such how can I perform the following pseudo-code with pure CSS?

if Webkit (Safari/Chrome) {
    #myDIV {margin-top:-3px}
} else if (Firefox) {
    #myDIV {margin-top:0px}
} else { // IE and other browsers
    #myDIV {margin-top:1px}
}

You can use a CSS Hack. However, I wouldn't recommend it.

For IE, you can include a separate CSS file or <style> tag inside a conditional comment , like this:

<!--[if IE] <tag> <![endif]-->

If its only one property, you don't need conditional comments for including other files. But if you want it that way, do it like SLaks already wrote. Another approach is just to add a property at the end of your specific class with a browser specific hack.

.foo {
  margin-top: 5px; // general property
  _margin-top: 2px; //IE 6 and below
}

Or you seperate your classes and add under your general class a browser specific class.

/* general */
foo {
   width : 20em;
}

/* IE 6 */
* html foo {
   width : 27em;
}

/* IE 7 */
* + html foo {
   width : 29em;
}

You can't really do this with pure CSS. The best way to do so would be using server-side code like ASP.NET or PHP to read the "user-agent" header of the HTTP request and determine what browser your visitors are using by searching for keywords in that string. For example, my user agent is:

Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3

What you could do is have a collection of if-else statements looking for strings in the user-agent like "Firefox" or "MSIE" or "WebKit", and then serve different individual CSS files depending on what browser is being used.

You could do the same thing with JavaScript, but remember that users may have JavaScript disabled, or more likely their device might not support it... whereas virtually any HTTP request will send a user-agent string.

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