CSS hacks & conditional statements

Don’t you wish sometimes there weren’t all these browsers out there for you to worry about your site breaking when developing a site with a nicely structured, table-less, semantic and valid (X)HTML/CSS markup? Well, guess what? They are here and won’t be going away very soon either. 😉

But that is what I love about what I do, is the challenge and finding better solutions to any issue that I might a come across when cross-browser testing any site that I work on. We all have done hacks in the past, including me, but it’s been said many times by many people that it is better stay away from them and rather use conditional statements where needed instead.

As you can see, the list is pretty long, but hopefully one day it will become shorter as certain browsers will diminish from the face of Earth as they should have long time ago. 😀

Common CSS hacks:

IE 6 and below

* html {}

IE 7 and below

*:first-child+html {} * html {}

IE 7 only

*+html {}

IE 7 and modern browsers only

html>body {}

Modern browsers only (not IE 7)

html>/**/body {}

IE8 Standards-Mode Only:

.test { color /*\**/: blue\9 }

All IE versions, including IE8 Standards Mode:

.test { color: blue\9 }

Opera versions 9 and below

html:first-child {}

Recent Opera version 9.5

@media all and (-webkit-min-device-pixel-ratio:10000), not all and (-webkit-min-device-pixel-ratio:0) { head~body {}}

Opera & Safari

@media screen and (-webkit-min-device-pixel-ratio:0) {
/* Safari-Opera specific declarations here */
}

Safari 3.1 & Google Chrome

body:nth-of-type(1) p{color: #333;}

Conditional statements for Internet Explorer:

Any version of IE

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

Only version

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

Versions less than version

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

Versions less than or equal to version

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

Versions greater than or equal to version

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

Versions greater than version

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

Conditional statements for Safari:

<link rel="stylesheet" media="screen and min-device-pixel-ratio: 0" type="text/css" href="/css/safari3.css"/>

Goes within “safari3.css” file:

@media screen and (-webkit-min-device-pixel-ratio:0){
html{
/*
need this so that Safari3 can
use window.getMatchedCSSRules to collect CSSStyleRule later
*/
list-style-image:none;
}
}