Cómo escribir un hack CSS para IE 11? [duplicar]


Esta pregunta ya tiene una respuesta aquí:

¿Cómo puedo hackear o escribir css solo para IE 11? Tengo un sitio web que se ve mal en IE 11.Acabo de buscar aquí y allá, pero no encontré ninguna solución todavía.

¿Hay algún selector css?

Author: Paul Sweatte, 2013-12-12

8 answers

Utilice una combinación de reglas CSS específicas de Microsoft para filtrar IE11:

<!doctype html>
<html>
 <head>
  <title>IE10/11 Media Query Test</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <style>
    @media all and (-ms-high-contrast:none)
     {
     .foo { color: green } /* IE10 */
     *::-ms-backdrop, .foo { color: red } /* IE11 */
     }
  </style>
 </head>
 <body>
  <div class="foo">Hi There!!!</div>
 </body>
</html>

Los filtros como este funcionan debido a lo siguiente:

Cuando un agente de usuario no puede analizar el selector (es decir, no es válido CSS 2.1), debe ignorar el selector y el siguiente bloque de declaración (si lo hay) también.

<!doctype html>
<html>
 <head>
  <title>IE10/11 Media Query Test</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <style>
    @media all and (-ms-high-contrast:none)
     {
     .foo { color: green } /* IE10 */
     *::-ms-backdrop, .foo { color: red } /* IE11 */
     }
  </style>
 </head>
 <body>
  <div class="foo">Hi There!!!</div>
 </body>
</html>

Referencias

 207
Author: Paul Sweatte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-23 21:29:31

A la luz del hilo evolutivo, he actualizado lo siguiente:

IE 6

* html .foo {property:value;}

O

.foo { _property:value;}

IE 7

*+html .foo {property:value;}

O

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

ES decir, 6 y 7

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

O

.foo { *property:value;}

O

.foo { #property:value;}

ES decir, 6, 7 y 8

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

IE 8

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

O

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

ES decir, Solo Modo Estándar de 8

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

ES decir, 8,9 y 10

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

IE 9 solamente

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

IE 9 y superior

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

IE 9 y 10

@media screen and (min-width:0\0) {
    .foo /* backslash-9 removes.foo & old Safari 4 */
}

ES decir, solo 10

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

IE 10 y superior

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

O

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

IE 11 (y superior..)

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

Alternativas de Javascript

Modernizr

Modernizr se ejecuta rápidamente en la carga de la página para detectar características; entonces crea un objeto JavaScript con los resultados, y añade clases a la elemento html

Agente de Usuario selección

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':'');

Añade (por ejemplo) lo siguiente al elemento html:

data-useragent='Mozilla/5.0 (compatible; M.foo 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'

Permite selectores CSS muy dirigidos, por ejemplo:

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

Nota de pie de página

Si es posible, identifique y corrija cualquier problema sin hacks. Apoyo mejora progresiva y la degradación de la. Sin embargo, este es un escenario de "mundo ideal" no siempre se puede obtener, como tal - lo anterior debería ayudar a proporcionar algunos buenos opcion.


Atribución / Lectura esencial

 180
Author: SW4,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-21 19:19:03

Aquí hay una solución de dos pasos aquí es un hack a IE10 y 11

    @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
}

Debido a que IE10 e IE11 son compatibles con-ms-high-cotrast, puede aprovechar esta ventaja para dirigirse a estos dos navegadores

Y si desea excluir el IE10 de esto debe crear un código específico de IE10 como sigue, está utilizando el truco del agente de usuario debe agregar este Javascript

var doc = document.documentElement;
doc.setAttribute('data-useragent', navigator.userAgent);

Y esta etiqueta HTML

<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">

Y ahora puedes escribir tu código CSS así

html[data-useragent*='MSIE 10.0'] h1 {
  color: blue;
}

Para más información, por favor consulte esta web,wil tutorail, Chris Tutorial


Y si quieres apuntar a IE11 y posteriores, esto es lo que he encontrado:

_:-ms-fullscreen, :root .selector {}

Aquí hay un gran recurso para obtener más información: browserhacks.com

 58
Author: Hbirjand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-08 02:56:56

He estado escribiendo estos y contribuyendo a BrowserHacks.com desde el otoño de 2013 this este que escribí es muy simple y solo soportado por IE 11.

<style type="text/css">
_:-ms-fullscreen, :root .msie11 { color: blue; }
</style>

Y por supuesto el div...

<div class="msie11">
    This is an Internet Explorer 11 CSS Hack
<div>

Así que el texto aparece en azul con Internet explorer 11. Diviértete con él.

-

Más IE y otros hacks CSS del navegador en mi sitio de prueba en vivo aquí:

ACTUALIZADO: http://browserstrangeness.bitbucket.io/css_hacks.html

ESPEJO: http://browserstrangeness.github.io/css_hacks.html

(Si también está buscando Hacks CSS de MS Edge, ahí es donde debe ir.)

 21
Author: Jeff Clayton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-04 13:31:04

Puede usar el siguiente código dentro de la etiqueta de estilo:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
/* IE10+ specific styles go here */  
}

A continuación se muestra un ejemplo que funcionó para mí:

<style type="text/css">

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
   #flashvideo {
        width:320px;
        height:240;
        margin:-240px 0 0 350px;
        float:left;
    }

    #googleMap {
        width:320px;
        height:240;
        margin:-515px 0 0 350px;
        float:left;
        border-color:#000000;
    }
}

#nav li {
    list-style:none;
    width:240px;
    height:25px;
    }

#nav a {
    display:block;
    text-indent:-5000px;
    height:25px;
    width:240px;
    }
</style>

Tenga en cuenta que dado que (#nav li) y (#nav a) están fuera de la pantalla @media ..., son estilos generales.

 6
Author: hoooman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-27 21:18:11

Puede usar js y agregar una clase en html para mantener el estándar de comentarios condicionales :

  var ua = navigator.userAgent,
      doc = document.documentElement;

  if ((ua.match(/MSIE 10.0/i))) {
    doc.className = doc.className + " ie10";

  } else if((ua.match(/rv:11.0/i))){
    doc.className = doc.className + " ie11";
  }

O usa una lib como bowser:

Https://github.com/ded/bowser

O modernizr para la detección de características:

Http://modernizr.com/

 1
Author: Liko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:45

Así que al final encontré mi propia solución a este problema.

Después de buscar a través de La documentación de Microsoft Me las arreglé para encontrar un nuevo IE11 solo estilo msTextCombineHorizontal

En mi prueba, compruebo los estilos IE10 y si son una coincidencia positiva, entonces compruebo el estilo solo IE11. Si lo encuentro, entonces es IE11+, si no, entonces es IE10.

Ejemplo de Código: Detectar IE10 e IE11 mediante Pruebas de capacidad CSS (JSFiddle)

voy a actualizar el ejemplo de código con más estilos cuando los descubro.

NOTA: Esto casi seguramente identificará IE12 e IE13 como "IE11", ya que esos estilos probablemente seguirán adelante. Agregaré más pruebas a medida que se implementen nuevas versiones, y espero poder confiar nuevamente en Modernizr.

Estoy usando esta prueba para el comportamiento alternativo. El comportamiento alternativo es solo un estilo menos glamoroso, no tiene una funcionalidad reducida.

 1
Author: HDT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-22 04:44:02

Encontré esto útil

<?php if (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/7.0; rv:11.0') !== false) { ?>
    <script>
    $(function(){
        $('html').addClass('ie11');
    });
    </script>
<?php } ?>

Añada esto bajo su <head> documento

 0
Author: ikke aviy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-17 06:46:42