X

Desplazamiento de imágenes con CSS

¿Te has dado cuenta de que a veces, cuando pasas el ratón por encima de una imagen, se queda en blanco durante un segundo y luego carga la imagen sobre la que pasas el ratón? Sin embargo, cuando vuelves a pasar el ratón por encima, todo es perfecto.

Aquí tienes un ejemplo de lo que quiero decir con mi imagen de la escalera subterránea (dividida en dos partes).

Esto es porque hay dos imágenes separadas que necesitan ser cargadas, y la segunda (en hover) toma tiempo extra para cargar cuando el efecto hover es disparado.

En este post, voy a mostrar cómo eliminar ese retraso utilizando una técnica CSS que carga toda la imagen a la vez, y mostrando una parte de ella.

Combinar la imagen

El primer paso para que esto funcione es combinar ambas mitades de la imagen en una sola. Para ello, puedes utilizar el editor de imágenes que prefieras. Sólo tienes que copiar ambas imágenes, duplicar su altura y pegar la inactiva encima de la activa.

Ladder 1Ladder 2Underground Ladder

La imagen del medio debería ser la que buscas. Ahora pasamos al CSS.

El código

El primer paso en el CSS es limitar la altura de la imagen a la mitad (básicamente para que sólo aparezca la escalera superior).

Para los propósitos de este tutorial, usaremos una clase llamada .rollover-tut. Como la imagen original de la escalera es de 153×149, usaremos este código CSS:

.rollover-tut {
altura: 149px;
anchura: 153px;
display: block;
}

Como estamos haciendo un enlace, usaremos el siguiente código HTML:

<a class="rollover-tut" href="#"></a>

En este punto, tu enlace debería parecerse a la imagen original de la escalera, sin efecto hover (todavía).

Ladder 1

Para que el efecto hover funcione, usaremos una propiedad CSS llamada background-position en la pseudoclase :hover.

.rollover-tut:hover {
background-position: 0 -149px;
}

Con el código CSS anterior, estarás desplazando la imagen de fondo 149 píxeles (recuerda, la altura de una imagen de escalera, o la mitad de las dos combinadas).

Una forma más fácil de recordar es utilizar el siguiente código hover en su lugar, que tendrá el mismo efecto que el anterior, y usted no tiene que recordar ningún número (punta de sombrero: Art Webb a través de los comentarios):

.rollover-tut:hover {
background-position: abajo a la izquierda;
}

Y esto es lo que obtienes:

Observe que ahora no hay retardo entre el efecto hover, ya que toda la imagen se carga a la vez.

Conclusión

Esta misma técnica se puede utilizar para casi cualquier efecto de imagen de fondo rollover. No estoy seguro de si alguno de ustedes ha revisado el diseño de mi blog personal últimamente, pero hago un uso extensivo de ella en casi todos los enlaces que utilizan una imagen de fondo (y el botón de envío en mi formulario de comentarios).

Espero que os haya gustado este consejo sobre CSS. Si tienes alguna idea para futuros consejos CSS, házmelo saber en los comentarios.

Comentarios   Deja una respuesta

  1. WOW! Nice tutorial! I like it!

  2. I will suggest you to examine the navigation of Apple’s official website navigation. Its an awesome use of CSS sprites. Another very effective use of css sprites can be seen here.

    http://www.problogdesign.com/wp-content/themes/pro-blog-design3/images/pbd-png-sprite.png

    See this image and then see how Martin broken that up on different places in his blog.:}

    1. There are definitely some more advanced ways of using this technique. The one I did was probably the simplest of the bunch.

      I also noticed something similar on CSS Tricks which I found interesting.

      http://cdn.css-tricks.com/wp-content/themes/CSS-Tricks-6/images/css-tricks.png

  3. Hey Leland,

    This is a very very good post for beginners who are still using 2 different images to create image rollovers – very well-written, short and sweet! Beautiful buttons too!

    I’ve just started using sprites recently on my clients’ projects (found it rather troublesome last time lol).

    I have a huge image which have all the icons, buttons that I needed for the website. Then I used background-position to display each elements. It can get really really tedious though if there are just too many elements but it’s really worth it

    Btw, it’s my first time here on your website. I love it so much, a lot of beautiful & subtle details

    1. Thanks Iwana, glad you liked the tutorial. Appreciate the kind words about my site as well. 😀

  4. This technique is called CSS Sprites.

    You could add one more state… Example: normal, hover, selected… And then for these three states you just change background position to top left, center left, and bottom left. Note: This method requires a little php code 🙂

    1. Thanks for the clarification, Milos. Maybe I’ll do a follow up post on how to do one with a selected/active state too, while still using one image.

      You mean CSS code (and not PHP) right?

      1. I mean CSS and a little bit of PHP. In this case we need that php to declare when link is in selected state. Here is example in short for web site with two pages (Page1 and Page2):

        Page1 code:

        <?php $thisPage="Welcome to Page1!"; ?>
        <head>
        <title><?php if ($thisPage!="") echo "$thisPage ::"; ?> mysite.com</title>
        ...
        </head>
        <body>
        <ul id="menu">
        <li><a class="page1" <?php if ($thisPage=="Welcome to Page1!") echo "id="selected""; ?> href="page1.php">Page1</a></li>
        <li><a class="page2" <?php if ($thisPage=="Welcome to Page2!") echo "id="selected""; ?> href="page2.php">Page2</a></li>
        </ul>
        ...content...
        </body>

        For page2 just $thisPage variable set to “Welcome to Page2!”

        CSS for links:
        #menu a {
        background-position: left top;
        }
        #menu a:hover {
        background-position: left center;
        }
        #menu a#selected, #menu a#selected:hover{
        background-position: left bottom;
        }

        That’s it 🙂 Cheers

        1. Awesome, I know in WordPress it sometimes spits out default classes for active page items if you use their functions.

          Like .current-page-item (for active pages) or .current-cat for active category archive.

          Thanks for the tips.

        2. No problem 😉 Cheers

  5. I love using one image for the normal and hover states. The only change I would make is for the background position of the hover state. Change it to:

    .rollover-tut:hover {
    background-position: bottom left;
    }

    That way if you change the size of the image, you don’t have to adjust the size.

    1. Ah…wow, I never thought of that but it makes perfect sense. Thanks for the tip.

      But if you changed the size of the image, wouldn’t you have to change the height and width in the first declaration?

      It still helps as it’s just one less thing to change.

  6. Nice and simple. Maybe this will stop people from using 2 images for rollovers.. well to single images =). Nice tut man, will come in handy for some people in the future =)

    1. Glad you liked the tut, Anto.

Añadir un comentario

Nos alegra que haya decidido dejar un comentario. Tenga en cuenta que todos los comentarios se moderan de acuerdo con nuestra política de privacidad , y que todos los enlaces son nofollow. NO utilice palabras clave en el campo del nombre. Tengamos una conversación personal y significativa.

WordPress Launch Checklist

La lista definitiva para lanzar WordPress

Hemos recopilado todos los elementos esenciales de la lista de comprobación para el lanzamiento de su próximo sitio web de WordPress en un práctico ebook.
Sí, envíeme el ¡gratuito!