Forums » CGI & CSS

CSS SPRITES COM CSS E LESS CSS

    • 467 posts
    31 de julho de 2013 19:37:26 ART

    CSS SPRITES COM CSS E LESS CSS

    Os dias de usar javascript para mudar imagens já eram!

    Rollovers podem ser criados usando CSS puro, que é uma técnica amplamente utilizada na web. Há muitos benefícios a usar CSS para rollovers. Ele não requer javascript, o que significa menos código em sua página, um rápido tempo de carregamento da página, e seus rollovers vão funcionar se o usuário tem o JavaScript desativado em seu navegador. Também é melhor para SEO, porque sempre terá de textos para os motores de busca.

    A maneira mais simples de usar o CSS para criar isso é ter duas imagens separadas e usá-las como imagens de fundo em um item. Digamos que você tenha um link que você queria ter uma fonte personalizada que não é web-safe (e você queria que ela tivesse um estado em foco com uma imagem diferente). Você pode criar a imagem e o estado de hover e aplicá-los em seu link com o seguinte CSS:

     
    a:link{
        display:block;
        width:200px;
        height:20px;
        text-indent:-9999px;
        background:url(images/sprite.jpg)
    }
    a:hover{
        display:block;
        width:200px;
        height:20px;
        text-indent:-9999px;
        background:url(images/sprite-hover.jpg)
    }

    Esta técnica é chamada de “substituição de imagem”, já que está substituindo o texto com uma imagem. O problema com essa técnica é que a imagem seguinte não é carregada até que se passe o mouse no link. Então, quando você passar o mouse no link, haverá um segundo ou dois, onde você não vê nenhuma imagem, até que a imagem carregue. Não é um tempo enorme, mas fica estranho ver um menu piscar quando se passar o mouse.

    CSS Sprites

    A solução para o problema citado acima é o uso de CSS Sprites. A teoria por trás desse técnica é que você coloca várias imagens juntas em um único arquivo que será carregado pelo navegador apenas uma vez; Melhorando o tempo de carregamento e acabando com o problema daspiscadas citadas acima. Esta imagem será usada como fundo em diversos objetos da página, e apenas com CSS você irá definir qual dos elementos nesta imagem irá aparecer.

    Exemplo

    Aqui temos o CSS Sprite que a Apple utiliza atualmente em sua navegação. Você pode ver que há várias imagens separadas e que todas fazem parte da navegação (:hover, :active,:link). Por ter apenas uma imagem sendo utilizada, na hora de chamar o fundo para o hover por exemplo, não vai piscar.

    apple-sprite

     
     

    Como usar o CSS Sprite

    Para mostrar ele em ação, irei mostrar os dois botões criados para esse post.Irá abrir no Codepen.io.
    botoes

    Crie seu CSS Sprite

    A chave para criar seu sprite é ter certeza de que tudo está exatamente alinhado, até o pixel. Nós estaremos usando pixels para mover as imagens com CSS, ter uma imagem malfeita só vai frustrá-lo. Deixe as imagens todas juntas, sem espaço em branco, e fazer uma nota das dimensões exatas em pixels de onde tudo está localizado.
    tamanhos

    Crie o CSS

    Agora que você tem seu arquivo de imagem pronto você pode criar seus links. Aqui está o código CSS para os meus botões. Neste exemplo, eu estou usando a mesma imagem para 2 estados diferentes do botão, o normal e o hover.

    .button{
      display:block;
      width:200px;
      height:50px;
      background:url('http://blog.lksvn.com.br/wp-content/uploads/2013/03/sprite.png')no-repeat00;
    }
    .button.blue{
      background-position:00;
    }
    .button.blue:hover{
      background-position:0-50px;
    }
     
    .button.red{
      background-position:-200px0;
    }
    .button.red:hover{
      background-position:-200px-50px;
    }

    Agora a estrutura HTML dos botões.

     
    <href="#"title=""class="button blue"></a>
    href="#"title=""class="button red"></a>

    Para vocês entenderem melhor como eu dei a posição de cada botão, criei uma imagem para cada um deles com suas posições. Ao usar o background-position eu posso mover o backgrounddo botão em horizontal (x) e vertical (y), sendo background-position: 0 0 (x,y respectivamente).

    Para um melhor entendimento sobre background-position, acesse esse link (em inglês).

    botao-1

    botao-1-2

    botao-2-1

    botao-2-2

     
     

    Versão em LESSCSS

    .button{
      margin:5px0;
      display:block;
      width:200px;
      height:50px;
      text-indent:-9999px;
      background:url('http://blog.lksvn.com.br/wp-content/uploads/2013/03/sprite.png')no-repeat00;
      &.blue{
        background-position:00;
        &:hover{
          background-position:0-50px;
        }
      }
      &.red{
        background-position:-200px0;
        &:hover{
          background-position:-200px-50px;
        }
      }
    }

    Este post foi editado por Oliveira Dario em 31 de julho de 2013 19:40:21 ART"
    • 3222 posts
    2 de janeiro de 2020 11:24:40 ART

    wow, great, I was wondering how to cure acne naturally. and found your site by google, learned a lot, now i’m a bit clear. I’ve bookmark your site and also add rss. keep us updated.   Halki Diabetes Remedy

    • 3222 posts
    2 de janeiro de 2020 11:34:14 ART

    I must admit that your post is really interesting. I have spent a lot of my spare time reading your content. Thank you a lot!   Unlock Your Hip Flexors

    • 3222 posts
    4 de janeiro de 2020 09:16:26 ART

    Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog.   Leptitox Supplement

    • 3222 posts
    4 de janeiro de 2020 11:30:37 ART

    I am always searching online for articles that can help me. There is obviously a lot to know about this. I think you made some good points in Features also. Keep working, great job !  Leptitox Supplement

    • 3222 posts
    4 de janeiro de 2020 11:55:07 ART

    I must admit that your post is really interesting. I have spent a lot of my spare time reading your content. Thank you a lot!    Knowledge Broker

    • 3222 posts
    5 de janeiro de 2020 06:25:58 ART

    It is extremely nice to see the greatest details presented in an easy and understanding manner.   Knowledge Broker Blueprint 2.0

    • 3222 posts
    5 de janeiro de 2020 07:01:18 ART

    I must admit that your post is really interesting. I have spent a lot of my spare time reading your content. Thank you a lot!   The Lost Book of Remedies

    • 3222 posts
    5 de janeiro de 2020 07:55:26 ART

    Excellent effort to make this blog more wonderful and attractive.   Custom Keto Diet

    • 3222 posts
    6 de janeiro de 2020 09:16:31 ART

    I must adI must admit that your post is really interesting. I have spent a lot of my spare time reading your content. Thank you a lot!mit that your post is really interesting. I have spent a lot of my spare time reading your content. Thank you a lot!     28 Day Keto Challenge

    • 3222 posts
    6 de janeiro de 2020 10:28:44 ART

    I’ve read some good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to create such a great informative website.       Text Chemistry

    • 3222 posts
    6 de janeiro de 2020 10:50:44 ART

    I must admit that your post is really interesting. I have spent a lot of my spare time reading your content. Thank you a lot!   Leptitox

    • 3222 posts
    7 de janeiro de 2020 06:05:58 ART

    I’ve read some good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to create such a great informative website.   His Secret Obsession

    • 3222 posts
    7 de janeiro de 2020 06:27:53 ART

    • 3222 posts
    7 de janeiro de 2020 06:43:54 ART

    Great survey. I'm sure you're getting a great response.   Leptitox

    • 3222 posts
    7 de janeiro de 2020 06:43:54 ART

    Great survey. I'm sure you're getting a great response.   Leptitox

    • 3222 posts
    16 de janeiro de 2020 05:01:02 ART

    I am a new user of this site so here i saw multiple articles and posts posted by this site,I curious more interest in some of them hope you will give more information on this topics in your next articles.    General Contractor

    • 3222 posts
    16 de janeiro de 2020 05:17:05 ART

    I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!   General Contractor

    • 3222 posts
    16 de janeiro de 2020 05:31:10 ART

    It is extremely nice to see the greatest details presented in an easy and understanding manner.   General Contractor

    • 3222 posts
    16 de janeiro de 2020 05:31:14 ART

    It is extremely nice to see the greatest details presented in an easy and understanding manner.   General Contractor

    • 3222 posts
    16 de janeiro de 2020 05:45:16 ART

    Really impressive post. I read it whole and going to share it with my social circules. I enjoyed your article and planning to rewrite it on my own blog.   General Contractor

    • 3222 posts
    16 de janeiro de 2020 06:00:20 ART

    Amazing knowledge and I like to share this kind of information with my friends and hope they like it they why I do   General Contractor

    • 3222 posts
    16 de janeiro de 2020 06:13:11 ART

    • 3222 posts
    16 de janeiro de 2020 06:13:13 ART
    General Contractor Wonderful blog post. This is absolute magic from you! I have never seen a more wonderful post than this one. You've really made my day today with this. I hope you keep this up!
    Este post foi editado por lifetime lifetime em 16 de janeiro de 2020 06:13:57 ART"
    • 3222 posts
    17 de janeiro de 2020 02:48:27 ART

    I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well..    General Contractor