views:

249

answers:

4

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}
}
A: 

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]-->
SLaks
A: 

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;
}
ChrisBenyamin
+1  A: 

You can use this script resource to check if the browser is webkit, mozilla, ie and more and apply CSS to those browsers only, in one file. I use it and it works perfectly.

CSS Browser Selector.

Kyle Sevenoaks
A: 

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.

Jake Petroules