CSS IE6/IE7/IE8/IE9を判別する条件付きのHTML classとハック

CSS IE6/IE7/IE8/IE9を判別する条件付きのHTML classとハック

2014-09-14
いっす!この記事は1年以上前に投稿されたもので、情報が古いかもしれません。ご注意ください!

条件付きのHTML class

条件付きコメントを使って、IEのみにHTMLのclassを付与。これにより簡単なCSS指定で、IE6、IE7、IE8、IE9の振り分けが可能になる。IEの場合のみテストボックスの背景色が変わる。各IE用の色は下のとおり。
他のブラウザの場合は白。

IE6      IE7      IE8      IE9    

ここの背景色が変わります。
HTML
<!--[if lt IE 7 ]> <html class="ie6"> <![endif]--> 
<!--[if IE 7 ]> <html class="ie7"> <![endif]--> 
<!--[if IE 8 ]> <html class="ie8"> <![endif]--> 
<!--[if IE 9 ]> <html class="ie9"> <![endif]--> 
<!--[if gt IE 9|!IE]><!--> <html> <!--<![endif]-->
CSS
.test{background: #ffffff;}
.ie6 .test{background: Orange;} 
.ie7 .test{background: SkyBlue;}
.ie8 .test{background: Yellow;} 
.ie9 .test{background: #FFC0CB;}

ハック

CSSは同じ指定をした場合 後に書いたものが適用されるので、ハックなし -> IE10以下 -> IE7以下 -> IE6 -> IE9, 10 -> IE10 の順番で書く。

IE6      IE7      IE8      IE9    

ここの背景色が変わります。
CSS
.test2 {
background: #ffffff; /* すべてのブラウザ */
background: Yellow\9; /* IE8 以下 */
*background: SkyBlue; /* IE7 以下 */
_background: Orange; /* IE6 */
}
.test2:not(:target) {
background: #FFC0CB\9; /* IE9 */
}
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
.test2:not(:target) {
    background-color: pink\9; /* IE10(\9なしでIE11にも適用) */
  }
}