Ocultar texto usando css


Tengo una etiqueta en mi html como esta:

<h1>My Website Title Here</h1>

Usando css quiero reemplazar el texto con mi logotipo real. Tengo el logotipo no hay problema a través de cambiar el tamaño de la etiqueta y poner una imagen de fondo a través de css. Sin embargo, no puedo averiguar cómo deshacerse del texto. Lo he visto hacer antes básicamente empujando el texto fuera de la pantalla. El problema es que no puedo recordar dónde lo vi.

 276
css
Author: Josh Crozier, 2009-01-23

29 answers

Esta es una manera:

h1 {
    text-indent: -9999px;                 /* sends the text off-screen */
    background-image: url(/the_img.png);  /* shows image */
    height: 100px;                        /* be sure to set height & width */
    width: 600px;
    white-space: nowrap;            /* because only the first line is indented */
}

h1 a {
    outline: none;  /* prevents dotted line when link is active */
}

Aquí está otra forma de ocultar el texto evitando el enorme cuadro de 9999 píxeles que creará el navegador:

h1 {
    background-image: url(/the_img.png);  /* shows image */
    height: 100px;                        /* be sure to set height & width */
    width:  600px;

    /* Hide the text. */
    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}
 402
Author: nicholaides,
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
2013-06-06 15:57:35

¿Por qué no simplemente usar:

h1 { color: transparent; }
 160
Author: nesono,
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
2011-11-04 22:49:03

Simplemente agregue font-size: 0; al elemento que contiene texto.

.hidden { font-size: 0; }
  font-size: 0; hides text. <span class="hidden"> You can't see me :) </span>
 138
Author: valk,
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-14 19:29:38

La forma más amigable para el navegador es escribir el HTML como

<h1><span>Website Title</span></h1>

Luego use CSS para ocultar el intervalo y reemplazar la imagen

h1 {background:url(/nicetitle.png);}
h1 span {display:none;}

Si puede usar CSS2, entonces hay algunas maneras mejores de usar la propiedad content, pero desafortunadamente la web no está 100% allí todavía.

 31
Author: Chris Farmiloe,
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
2015-07-02 12:26:47

Jeffrey Zeldman sugiere la siguiente solución:

.hide-text {
  text-indent: 100%;
  white-space: nowrap;
  overflow: hidden;
}

Debería ser menos recursos que -9999px;

Por favor, lea todo sobre esto aquí:

Http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/

 18
Author: maartenmachiels,
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-11-14 15:01:17

Ocultar texto con la accesibilidad en mente:

Además de las otras respuestas, aquí hay otro enfoque útil para ocultar texto.

Este método oculta efectivamente el texto, pero permite que permanezca visible para los lectores de pantalla. Esta es una opción a considerar si la accesibilidad es una preocupación.

.sr-only {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0,0,0,0);
    border: 0;
}

Vale la pena señalar que esta clase se utiliza actualmente en Bootstrap 3.


Si estás interesado en leer sobre accesibilidad:

 16
Author: Josh Crozier,
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 10:31:37

Ver mezzoblue para un buen resumen de cada técnica, con fortalezas y debilidades, además de ejemplo html y css.

 15
Author: darasd,
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
2009-05-08 10:54:52

No use { display:none; } Hace que el contenido sea inaccesible. Desea que los lectores de pantalla vean su contenido y lo modifiquen visualmente reemplazando el texto con una imagen (como un logotipo). Mediante el uso de text-indent: -999px; o un método similar, el texto sigue ahí, pero no visualmente. Utilice display:none, y el texto se ha ido.

 6
Author: jensimmons,
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
2013-06-06 16:00:47

Tantas soluciones complicadas.

El más fácil es simplemente usar:

color:rgba(0,0,0,0)
 6
Author: Pier,
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
2016-08-12 20:38:45

Puede usar la propiedad css background-image y z-index para asegurarse de que la imagen permanezca delante del texto.

 5
Author: Jobo,
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
2013-06-06 16:04:34

¿Por qué no usas:

<li><a href="#">bla</a></li>

a {
    opacity: 0.0;
    font-size: 1px;
}

li {
    background-image: url('test.jpg');
}

Si no tienes ningún elemento span o div, funciona perfectamente para enlaces.

 5
Author: Hans,
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-08-06 13:21:46

La respuesta es crear un span con la propiedad

{display:none;}

Puedes encontrar un ejemplo en este sitio

 4
Author: Andrei Krotkov,
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
2009-01-23 01:24:14

Esta es en realidad un área madura para la discusión, con muchas técnicas sutiles disponibles. Es importante que seleccione / desarrolle una técnica que satisfaga sus necesidades incluyendo: lectores de pantalla, imágenes/css/scripting combinaciones de encendido/apagado, seo, etc.

Aquí hay algunos buenos recursos para comenzar en el camino del reemplazo de imágenes standardista técnicas:

Http://faq.css-standards.org/Image_Replacement

Http://www.alistapart.com/articles/fir

Http://veerle.duoh.com/blog/links/#l-10

 4
Author: willoller,
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
2009-01-23 04:02:25
<style>
body {
     visibility:hidden
}
body .moz-signature p{
    visibility:visible
}
</style>

Lo anterior funciona bien en el último Thunderbird también.

 4
Author: kamalesh,
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
2011-07-03 09:52:28

Use la etiqueta de condición para diferentes navegadores y use css para colocar height:0px y width:0px también hay que colocar font-size:0px.

 3
Author: kedar,
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
2012-06-07 14:53:26
h1 {
    text-indent: -3000px; 
    line-height: 3000px;
    background-image: url(/LOGO.png);
    height: 100px; width:  600px;  /* height and width are a must */

}
 2
Author: vencedor,
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
2012-01-26 17:11:46

Si el punto es simplemente hacer que el texto dentro del elemento sea invisible, establezca el atributo color para que tenga 0 opacidad utilizando un valor rgba como color:rgba(0,0,0,0); limpio y simple.

 2
Author: Cafe Coder,
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-06-19 08:49:41

Pruebe este código para acortar y ocultar el texto

.hidetxt{

  width: 346px;
  display: table-caption;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: no-drop;
  
}

.hidetxt:hover { 

  visibility: hidden;
  
}
<div class="hidetxt">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when</p>
</div>

O para ocultar el uso en su clase css .hidetxt { visibility: hidden; }

 2
Author: omar kerr,
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
2015-04-17 03:21:40

Repalce el contenido con el CSS

 h1{  font-size: 0px;}
 h1:after {
    content: "new content";
    font-size: 15px;
  }
 2
Author: Hossein Hajizadeh,
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-07-03 08:55:56

Normalmente uso:

span.hide
{
  position:fixed;
  right:-5000px;
}
 1
Author: Anze,
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
2012-05-03 08:45:13

Si podemos editar el marcado, la vida puede ser más fácil, simplemente elimine el texto y sea feliz. Pero a veces el marcado fue colocado por código JS o simplemente no se nos permite editarlo en absoluto, lástima que css se convirtió en la única arma puesta a nuestra disposición.

No podemos colocar un <span> envolviendo el texto y ocultar toda la etiqueta. Por cierto, algunos navegadores no solo ocultan elementos con display:none, sino que también deshabilitan los componentes dentro.

Tanto font-size:0px como color:transparent pueden ser buenas soluciones, pero algunos navegadores no los entiendo. No podemos confiar en ellos.

Sugiero:

h1 {
  background-image: url(/LOGO.png);  /* Our image */
  text-indent: -3000px;  /* Send text out of viewable area */
  height: 100px; width: 600px;  /* height and width are a must, agree */
  overflow:hidden;  /* make sure our size is respected */
}

Usando overflow:hidden refuerza nuestro ancho y alto. Algunos navegadores (no los nombrarán... IE ) puede leer anchura y altura como min-width y min-height. Quiero evitar que la caja se amplíe.

 1
Author: Francisco,
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
2012-10-29 02:02:59

Usar el valor cero para font-size y line-height en el elemento hace el truco para mí:

<style>
    .text {
        display: block;
        width: 200px;
        height: 200px;

        font-size: 0;
        line-height: 0;
    }
</style>

<span class="text">
    Invisible Text
</span>
 1
Author: HelpNeeder,
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
2016-01-05 20:07:07

Para ocultar texto de html use la propiedad text-indent en css

.classname {
 text-indent: -9999px;
 white-space: nowrap; 
}

/* para texto dinámico necesita agregar espacio en blanco, para que su css aplicado no moleste. nowrap significa que el texto nunca se ajustará a la siguiente línea, el texto continúa en la misma línea hasta que se encuentra una etiqueta <br>

 1
Author: urmila manjarikar,
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
2016-02-17 10:00:26

No recuerdo dónde recogí esto, pero lo he estado usando con éxito durante siglos.

  =hide-text()
    font: 0/0 a
    text-shadow: none
    color: transparent

Mi mixin está en sass, sin embargo, puede usarlo de la manera que considere conveniente. Para una buena medida, generalmente mantengo una clase .hidden en algún lugar de mi proyecto para adjuntarla a los elementos para evitar la duplicación.

 1
Author: itsfreshmade,
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-22 14:28:52

Una de las formas en que logro esto es usar :before o :after. He utilizado este enfoque durante varios años, y particularmente funciona muy bien con iconos vectoriales glifos.

h1 {
    position: relative;
    text-indent: -9999px;                 /* sends the text off-screen */
    }
h1:before {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    display: block;
    width: 600px;
    height: 100px;
    content: ' ';
    background: transparent url(/the_img.png) 0 0 no-repeat;
    }
 1
Author: Pegues,
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-02-26 16:05:47

Esto funcionó para mí con span (validación knockout).

<span class="validationMessage">This field is required.</span>

.validationMessage {
    background-image: url('images/exclamation.png');
    background-repeat: no-repeat;
    margin-left: 5px;
    width: 16px;
    height: 16px;
    vertical-align: top;

    /* Hide the text. */
    display: inline-block;
    overflow: hidden;
    font-size: 0px;
}
 0
Author: Karson,
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
2013-08-30 03:15:24

Una solución que funciona para mí :

HTML

<div class="website_title"><span>My Website Title Here</span></div>

CSS

.website_title {
    background-image: url('../images/home.png');
    background-repeat: no-repeat;
    height: 18px;
    width: 16px;
}

.website_title span {
    visibility: hidden;
}
 0
Author: Sébastien Gicquel,
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-12-16 21:34:56

La mejor respuesta funciona para texto corto, pero si el texto se envuelve, solo aparece en la imagen.

Una forma de hacerlo es detectar errores con un controlador jquery. Intente cargar una imagen, si falla lanza un error.

$('#logo img').error(function(){
    $('#logo').html('<h1>My Website Title Here</h1>');
});

Véase CÓDIGO DE MUESTRA

 -1
Author: Shanimal,
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
2015-01-16 00:05:24
h1{
   background:url("../images/logo.png") no-repeat;
   height:180px;
   width:200px;
   display:inline-block;
   font-size:0px !important;
   text-intent:-9999999px !important;
   color:transparent !important;
 }
 -1
Author: Harden Rahul,
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
2016-03-16 05:52:13