Pregunta

Quiero apuntar a IE7 e IE8 con CSS compatible con W3C. A veces, arreglar CSS para una versión no soluciona para la otra. ¿Cómo puedo lograr esto?

¿Fue útil?

Solución

Dirige explícitamente las versiones de IE sin hacks usando HTML y CSS

Usa este enfoque si no quieres hacks en tu CSS. Agregue una clase exclusiva del navegador al elemento <html> para que pueda seleccionar según el navegador más tarde.

Ejemplo

<!doctype html>
<!--[if IE]><![endif]-->
<!--[if lt IE 7 ]> <html lang="en" class="ie6">    <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="ie7">    <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="ie8">    <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="ie9">    <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
    <head></head>
    <body></body>
</html>

Luego, en su CSS puede acceder muy estrictamente a su navegador de destino.

Ejemplo

.ie6 body { 
    border:1px solid red;
}
.ie7 body { 
    border:1px solid blue;
}

Para obtener más información, consulte http://html5boilerplate.com/

Target IE versiones con CSS " Hacks "

Más a tu punto, aquí están los hacks que te permiten apuntar a versiones de IE.

Use " \ 9 " para apuntar a IE8 y menos.
Utilice & Quot; * & Quot; para apuntar a IE7 y menos.
Utilice & Quot; _ & Quot; para orientar IE6.

Ejemplo:

body { 
border:1px solid red; /* standard */
border:1px solid blue\9; /* IE8 and below */
*border:1px solid orange; /* IE7 and below */
_border:1px solid blue; /* IE6 */
}

Actualización: Target IE10

IE10 no reconoce las declaraciones condicionales, por lo que puede usar esto para aplicar un " ie10 " clase al <=> elemento

<!doctype html>
    <html lang="en">
    <!--[if !IE]><!--><script>if (/*@cc_on!@*/false) {document.documentElement.className+=' ie10';}</script><!--<![endif]-->
        <head></head>
        <body></body>
</html>

Otros consejos

Recomendaría buscar comentarios condicionales y hacer una hoja separada para los IE con los que tiene problemas.

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

La respuesta a tu pregunta

Una forma completamente válida de seleccionar todos los navegadores, pero IE8 y versiones inferiores es utilizar la pseudoclase :not(). Dado que las versiones IE 8 y posteriores no son compatibles con :first-child, los selectores que lo contienen se ignoran. Esto significa que podría hacer algo como esto:

p {color:red;}
p:not([ie8min]) {color:blue;}

Esto todavía es CSS completamente válido, pero hace que IE8 y versiones inferiores representen diferentes estilos (y también Opera < 9.5 y Safari < 3.2).

Otros trucos

Aquí hay una lista de todos los selectores específicos del navegador CSS completamente válidos que pude encontrar, excepto para algunos que parecen bastante redundantes, como los que seleccionan solo 1 tipo de navegador antiguo ( 1 , 2 ):

/******  First the hacks that target certain specific browsers  ******/
* html p                        {color:red;} /* IE 6- */
*+html p                        {color:red;} /* IE 7 only */
@media screen and (-webkit-min-device-pixel-ratio:0) {
    p                           {color:red;}
}                                            /* Chrome, Safari 3+ */
p, body:-moz-any-link           {color:red;} /* Firefox 1+ */
:-webkit-any(html) p            {color:red;} /* Chrome 12+, Safari 5.1.3+ */
:-moz-any(html) p               {color:red;} /* Firefox 4+ */

/****** And then the hacks that target all but certain browsers ******/
html> body p                  {color:green;} /* not: IE<7 */
head~body p                   {color:green;} /* not: IE<7, Opera<9, Safari<3 */
html:first-child p            {color:green;} /* not: IE<7, Opera<9.5, Safari&Chrome<4, FF<3 */
html>/**/body p               {color:green;} /* not: IE<8 */
body:first-of-type p          {color:green;} /* not: IE<9, Opera<9, Safari<3, FF<3.5 */
:root p                       {color:green;} /* not: IE<9, Opera<9.5 */
body:not([oldbrowser]) p      {color:green;} /* not: IE<9, Opera<9.5, Safari<3.2 */

Créditos & amp; fuentes:

Para obtener una lista más completa a partir de 2015:

IE 6

* html .ie6 {property:value;}

o

.ie6 { _property:value;}

IE 7

*+html .ie7 {property:value;}

o

*:first-child+html .ie7 {property:value;}

IE 6 y 7

@media screen\9 {
    .ie67 {property:value;}
}

o

.ie67 { *property:value;}

o

.ie67 { #property:value;}

IE 6, 7 y 8

@media \0screen\,screen\9 {
    .ie678 {property:value;}
}

IE 8

html>/**/body .ie8 {property:value;}

o

@media \0screen {
    .ie8 {property:value;}
}

Solo modo estándar IE 8

.ie8 { property /*\**/: value\9 }

IE 8,9 y 10

@media screen\0 {
    .ie8910 {property:value;}
}

solo IE 9

@media screen and (min-width:0) and (min-resolution: .001dpcm) { 
 // IE9 CSS
 .ie9{property:value;}
}

IE 9 y superior

@media screen and (min-width:0) and (min-resolution: +72dpi) {
  // IE9+ CSS
  .ie9up{property:value;}
}

IE 9 y 10

@media screen and (min-width:0) {
    .ie910{property:value;}
}

solo IE 10

_:-ms-lang(x), .ie10 { property:value\9; }

IE 10 y superior

_:-ms-lang(x), .ie10up { property:value; }

o

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
   .ie10up{property:value;}
}

IE 11 (y superior ..)

_:-ms-fullscreen, :root .ie11up { property:value; }

Alternativas de Javascript

Modernizr

  

Modernizr se ejecuta rápidamente en la carga de la página para detectar funciones; entonces   crea un objeto JavaScript con los resultados y agrega clases al   elemento html

Selección de agente de usuario

El Javascript:

var b = document.documentElement;
        b.setAttribute('data-useragent',  navigator.userAgent);
        b.setAttribute('data-platform', navigator.platform );
        b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Agrega (por ejemplo) lo siguiente al elemento html:

data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'

Permitir selectores CSS muy específicos, por ejemplo:

html[data-useragent*='Chrome/13.0'] .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;
}

Nota al pie

Si es posible, evite la orientación del navegador. Identifique y solucione cualquier problema que identifique. Admite mejora progresiva y degradación elegante . Con eso en mente, este es un escenario de "mundo ideal" que no siempre se puede obtener en un entorno de producción, como tal, lo anterior debería ayudar a proporcionar algunas buenas opciones.


Atribución / Lectura esencial

Bueno, realmente no tiene que preocuparse de que el código IE7 no funcione en IE8 porque IE8 tiene modo de compatibilidad (puede procesar las páginas igual que IE7). Pero si todavía desea apuntar a diferentes versiones de IE, una forma que se ha hecho durante un tiempo ahora es usar comentarios condicionales o comience su regla CSS con a * para apuntar a IE7 y a continuación . O podría prestar atención al agente de usuario en los servidores y distribuir un archivo CSS diferente en función de esa información.

El problema real no es IE8, sino los hacks que usas para versiones anteriores de IE.

IE8 está bastante cerca de cumplir con los estándares, por lo que no debería necesitar ningún truco para ello, tal vez solo algunos ajustes. El problema es si está utilizando algunos hacks para IE6 e IE7; deberá asegurarse de que solo se apliquen a esas versiones y no a IE8.

Hace un tiempo hice que el sitio web de nuestra compañía fuera compatible con IE8. Lo único que realmente cambié fue agregar la metaetiqueta que le dice a IE que las páginas son compatibles con IE8 ...

Lo hice usando Javascript. Agrego tres clases css al elemento html:

ie<version>
lte-ie<version>
lt-ie<version + 1>

Entonces, para IE7, agrega ie7, lte-ie7 ..., lt-ie8 ...

Aquí está el código de JavaScript:

(function () {
    function getIEVersion() {
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf('MSIE ');
        var trident = ua.indexOf('Trident/');

        if (msie > 0) {
            // IE 10 or older => return version number
            return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
        } else if (trident > 0) {
            // IE 11 (or newer) => return version number
            var rv = ua.indexOf('rv:');
            return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
        } else {
            return NaN;
        }
    };

    var ieVersion = getIEVersion();

    if (!isNaN(ieVersion)) { // if it is IE
        var minVersion = 6;
        var maxVersion = 13; // adjust this appropriately

        if (ieVersion >= minVersion && ieVersion <= maxVersion) {
            var htmlElem = document.getElementsByTagName('html').item(0);

            var addHtmlClass = function (className) { // define function to add class to 'html' element
                htmlElem.className += ' ' + className;
            };

            addHtmlClass('ie' + ieVersion); // add current version
            addHtmlClass('lte-ie' + ieVersion);

            if (ieVersion < maxVersion) {
                for (var i = ieVersion + 1; i <= maxVersion; ++i) {
                    addHtmlClass('lte-ie' + i);
                    addHtmlClass('lt-ie' + i);
                }
            }
        }
    }
})();

Posteriormente, utiliza la clase .ie<version> css en su hoja de estilo como se describe en potench.

(Utilizó la función detectIE de Mario en Compruebe si el usuario está usando IE con jQuery )

El beneficio de tener lte-ie8 y lt-ie8, etc. es que puede apuntar a todos los navegadores menores o iguales a IE9, es decir IE7 - IE9.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top