banner



How To Create A Css Sprite

How to create Responsive Retina CSS sprites

Updated 2019-10-27 with animation example.

In this tutorial, you are going to learn how you create responsive CSS sprites with support for HighDPI / Retina displays.

What you get from this:

  • Faster web page downloads
  • Automated building of your CSS sprite sheets
  • Optimized PNG files (using pngquant algorithm)
  • Responsive images

4 Reasons why you should use CSS sprites for your images

Reasons Google gives us (see Google PageSpeed Insights):

  • If many small images are combined into one large image, the browser will require fewer server connections, which can increase parallelism.
  • Bytes are saved from the overhead of each individual request (both the HTTP headers and the image headers); depending on how well the large PNG compresses, this can end up saving a substantial amount of bandwidth.
  • In some browsers, it is faster to decode one large image than several small ones.

TexturePacker also optimizes and compressed your PNG files. You can use 8-bit PNGs in many cases without any loss of image quality.

Input input data

All images are at a high resolution, ready to look nice on retina displays. They are designed to be smaller on the webpage.

The comet has two images: The second images appears after hovering the image with the mouse.

The images are all cropped and saved with Photoshop's Quick Export as PNG:

banner.png: 1600x394, 311K

comet.png
200x200, 67K

comet-hover.png
200x200, 59K

earth.png
200x200, 56K

mars.png
200x200, 56K

All example images in this tutorial are copyright by StockUnlimited.

Creating your sprite sheet

Download TexturePacker from here — it's available for Windows, MacOS and Linux:


TexturePacker can create sprite sheets for all kinds of projects — including many game development frameworks. First, choose the CSS exporter:

Choose TexturePacker's CSS sprite exporter

Add your sprites to TexturePacker: Drag & drop the folder containing your sprites into its main window.

TexturePacker scans the folder for image files — including PSD, PNG, JPG and many other formats. All files contained in the folder are automatically added to your sprite sheet.

To add more sprites in the future simply add them to the folder and re-open TexturePacker.

Add sprites to pack into the CSS sprite sheet.

The sprites show up in the center screen as a packed sprite sheet.

Click the blue folder next to Data file and enter the name of a .css file to store. The sprite sheet image is stored next to the CSS file for now. You can change this later.

Finally, press publish. This saves your sprite sheet as PNG and CSS files.

Using the sprite sheet

All you have to do is to create some simple HTML file like this:

            <!DOCTYPE html> <html lang="en">     <head>         <meta charset="utf-8">         <link rel="stylesheet" href="sprites.css">     </head>     <body>         <i class="banner"></i>          <i class="comet"></i>         <i class="earth"></i>         <i class="mars"></i>     </body> </html>          

Fixed size images (standard resolution)

This includes the sprites as inline elements with a fixed size — just like an <img> tag would do:

            <i class="earth"></i> <i class="mars"></i>          

Images with ::hover and other effects (standard resolution)

The comet responds to the hover and displays a different image as soon as the mouse is over the image:

<-- move your mouse over this image

TexturePacker derives the matching CSS selectors from the file's name. Supported suffixes are:

  • -link
  • -visited
  • -focus
  • -active
  • -hover

Using the 2 files comet.png and comet-hover.png is already enough to create the effect.

Responsive images (standard resolution)

To make an image responsive simply use the <div> tag instead of <i>. This image scales with the browser's width:

            <div class="banner"></div>          

Enabling high resolution / Retina display support

Modern mobile phones, tablets, and computers come with high-resolution displays. Let's provide your web page visitors with high-quality images.

As mentioned above: The input sprites are at high resolution. We want them to appear smaller on the web page. But they should also adapt to high-resolution displays.

Nothing easier than that: Click on the small cog next to the Scaling variants. A new sheet opens.

Creating Retina CSS sprites

Select CSS: Retina / HighDPI from the Presets and press Apply.

The preset will create 2 sprite sheets:

  • sheet-2x.png — with a scale factor of 1
  • sheet.png — with a scale factor of 0.5

It is important to design at a high resolution and scale down. If you do it in the other direction, you'll just end up with blurry images.

Close the dialog with a click on close.

Please note the change in the Texture file text field: {v} is now inserted into the sprite's image name: sprite{v}.png.

The {v} is a place holder that is replaced with the scaling variant name to create the -2x image files.

Press Publish sprite sheet and check your output folder for the two image files.

You'll still only get one css file. It contains the media queries to switch between the image files.

Responsive, Retina / HighDPI CSS Sprites

Responsive image

Resize your browser to see the effect.

            <div class="banner"></div>          

Static images

            <i class="earth"></i> <i class="mars"></i>          

Animated with ::hover

<-- Move your mouse over the image

You can of course also create animated responsive banners by replacing the <i> with a <div> tag.

Optimizing images to use less bandwidth

The current image set uses 554K, which is about the same as the single images summed up: 549K. The gain for your web page is that this requires 2 network connections instead of 5:

  • sprites.css
  • sprites.png

The images don't contain transparency so you could easily switch to JPG files instead of PNGs. Or you could use 8 bit PNG files — which is great if your sprites contain transparency.

Simply switch the Texture format to PNG-8 and set Dithering to PngQuant High.

Optimizing PNGs to reduce memory

Press publish to save the updated sprite sheet. The resulting image file is now 138K — only 24% of the original size!

How to animating css sprites with pure Javascript

There are several options to animate a sprite sheet. I'll show you a way to do it with pure Javascript here. You can of course also use one of the many Javascript frameworks...

            <script>     function animate()     {         const cssClass="animation";         let animatedElements = document.getElementsByClassName(cssClass);          for (let el of animatedElements) {             const frameSpeed = el.getAttribute("data-speed") || 100;              setInterval(function(){                 const frames = el.getAttribute("data-frames").split(",");                 let frame = el.getAttribute("data-frame") || 0;                  frame = (++frame) % frames.length;                 el.setAttribute("data-frame", frame);                  el.className=cssClass+' '+frames[frame]             }, frameSpeed);         }     } </script>          

And here is how to use this function:

            <i class="animation earth" data-speed="1200" data-frames="earth,mars,comet"></i> <i class="animation earth" data-speed="800" data-frames="earth,mars,comet"></i> <i class="animation earth" data-speed="400" data-frames="earth,mars,comet"></i>  <script>     animate(); </script>          

Add the following attributes to the items you want to animate:

  • class='animation' — required for the script to detect animations
  • data-speed="speed" — the delay between frames in ms
  • data-frames="frame1,frame2,..." — a comma separated list of animation frames

Fine tuning your sprite sheet

Adding a prefix to the CSS sprite classes

Sometimes you want to create a prefix for your sprites to make sure that they don't mess with your other CSS class names.

Click on the button Advanced Settings at the bottom of the right panel in TexturePacker. In section Data is a field called Sprite prefix. You can put in a string like image- or icon-. The name is placed before all your sprites.

Placing the sprite sheet and images in different folders

You can use the Texture file field to save your sprite sheets in a different folder. Make sure to add the {v} at the end of your file name.

Use the Texture path field (Advanced Settings / Data) to specify the path to the image inside the CSS file.

Changing the media query for retina

We've selected a media query for the retina images which we think makes sense. The default value is

(-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi)

Use Media query 2x (Advanced Settings / Data) to adjust it.

Still not satisfied?

TexturePacker's application folder contains the source code for the exporter. You can adapt it to whatever you need.

Building your CSS sprites from command line

You can use TexturePacker from command line to build your sprite sheets like this:

            TexturePacker --format css \               --data sprites.css \               --sheet sprites{v}.png \               --variant 1:-2x \               --variant 0.5: \               --force-identical-layout \               your_sprites_folder          
  • --format css — sets the output format
  • --data sprites.css — specifies where to write the CSS file
  • --sheet sprites{v}.png — where to write the PNG files. {v} is replaced with -2x for retina sprites
  • --variant 1:-2x — use scale factor 1 for the high res sprites, suffix: -2x
  • --variant 0.5: — use scale factor 0.5 for the low res sprites, no suffix
  • --force-identical-layout — make sure that the layout of the high and low resolution sheet is identical
  • your_sprites_folder — the folder containing your sprites

An even simpler way is to configure your sprite sheet in the UI and save a .tps project file. Use this command line to update your sheets:

            TexturePacker mysprites.tps          

The result: Responsive, Retina / HighDPI CSS Sprites

Responsive banner

Resize your browser to see the effect.

            <div class="banner"></div>          
            <i class="earth"></i> <i class="mars"></i>          

::hover

<-- Move your mouse over the image

Animated (playing at different speeds)

The example images in this tutorial are copyright by StockUnlimited.

Did you like the tutorial? Please share!

How To Create A Css Sprite

Source: https://www.codeandweb.com/texturepacker/tutorials/how-to-create-responsive-retina-css-sprites

Posted by: adamsfirwass66.blogspot.com

0 Response to "How To Create A Css Sprite"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel