How to make sprites. The last step is to write the jQuery code that creates the animation. Why use CSS sprites

What is the advantage of using CSS sprites? Imagine that you have six images used in the layout of a web page, and the browser needs to load them all separately. If they were combined into one image, you could significantly increase loading speed. This will reduce the number of server calls required to render a page, making your site faster.

Instead of loading six images, it would now load one. In that advantage of CSS sprites

Most web pages use several small images. Background images, arrows, icons, menu items, etc. These tiny images really make a difference when you consider their impact on page loading speed.

Each image must be uploaded. The browser must request the server for an image, the server must send it, and then the browser must display it. If it were just one or two images, special problems would not have arisen. But since many more pictures are loaded, this negatively affects the page loading speed.

The solution is to use sprites, which combine several small ones into one image, so web pages can load much faster.

How to combine images into a sprite

There are two main steps to creating CSS sprites. First you have to create an image and then place it.

Combining images

Let's say we have two images that we want to combine into one. To create a sprite, we need to know the size of the images. We'll look at an example where both images are the same size (50 by 50 pixels):

To combine them, we need to create an image that is 100 by 50 pixels. Let's call it "sprite.png". Now that we have the merged image, we can use its information to correct display on the web page.

The merged image is 50 pixels wide and 100 pixels high. So we can say that the first image (megaphone) is located in the top 50 pixels of the new image, and the second (smiley) is located in the bottom 50 pixels of the image. We will show the top half of the image when you need to display a megaphone, and the bottom half when you need to display a smiley face. Implementation of creating CSS sprites:

Positioning an image on a page

In this example we will use pictures as background images located in div elements. We will create empty ones div tags to display images. If we need to display an image of a megaphone on our page, we use the “megaphone” CSS class:

Megaphone (width:50px; height:50px; background:url(images/sprite.png) 0 0px;)

The above CSS code specifies the width and height of the megaphone image (50 by 50 pixels), it also calls the "sprite.png" image, which is merged. The “0 0px” part of the code is responsible for displaying the sprite. Specifying the image to start at "0 0px" means that it should be rendered at 0 pixels on the X axis and 0 pixels on the Y axis. This means “start image output from the top” and “start image output from the left”.

Since we defined the width and height of the image in CSS, only the top 50 pixels (where the megaphone is located) will be displayed. Thus, the smiley will not be visible at all. Now let's display a smiley face and see how the sprite's CSS code changes. We'll create a CSS class called "smile":

Smile (width:50px; height:50px; background:url(images/sprite.png) 0 -50px;)

Notice that we're still specifying the same width and height, calling the same image, but we've changed this part: "0 -50px". This way we specify that the image should start 50 pixels below the starting coordinate point (-50px ). Because the smiley face design does not start at the beginning, but 50 pixels down from the top of the merged image.

Now that the CSS is specified, we can call the div wherever we need to display the image. Where we need to display a megaphone, we place an empty one div block with class "megaphone":

When we need to display a smiley, we place a div with the “smile” class:

This is the basic principle of how to make a CSS sprite. There are many ways to implement this and it is better to choose the one that suits you best. In this article we showed how sprites work, but we didn't go into detail about them.

The translation of the article “How to use CSS sprites” was prepared by the friendly project team.

Hello, dear friends. Today we will continue to optimize images on our sites to speed up loading speed. As you remember from , we learned how to optimize any images for the site, both individually and in bulk.

And today our topic is also devoted to image optimization, but much more complex than last time. Namely, today I will tell and show you how to create CSS sprites to speed up site loading. It is this technology that can significantly increase the site loading speed.

What are CSS sprites

In general, sprite technology was first invented by animators at Disney. After which this technology began to be actively used in computer games and finally in web design.

In animation and computer games, sprite technology allows you to overlay characters and control their actions against the background of the finished scene.

In web design, sprites allow you to manipulate the image and visual effects. Example: on my website. Initially, you see one image, but when you move your mouse over the rocket, you see another image. But in reality it is one image.

This is the whole point of CSS sprites.

Why use CSS sprites

Well, of course, to speed up the site loading speed. Let's take my blog as an example. If you look closely, there are many design elements on my blog that are presented as separate files (images).

Design elements that can be replaced with a sprite

IN total this is 19 individual images. All of them are optimized and weigh very little. And this is very good. But the sheer number of images creates 19 HTTP request ov to the server. And all these request-response slow down the loading of the site. Or you can replace these 19 images with one or two.

Thus, the volume of the downloaded image and the number of requests to the server are reduced. And therefore the site loading speed increases.

What images should be combined into CSS sprites?

There is no need to think that absolutely all images should be combined. This is not at all necessary. In order to find out which images should be combined, I advise you to use the already familiar GTmetrix service.

Here you can also see recommendations for creating sprites. Or rather, the recommendation of the CSS sprite generator SpriteMe. With this generator you can easily create the sprites you need. But it didn’t help me, so I had to do everything myself.

How to create CSS sprites

Now I’ll try to figuratively explain how it works. So, imagine - the entire website template is a solid frame with many cells for insertion graphic elements. And behind this frame is a solid image with many graphic design elements. And this image is controlled by CSS help styles. That is, using CSS styles you can insert the desired image fragment into any window of the frame. I hope I explained it clearly. So let's get started.

After the GTmetrix service has prompted you or you have decided which files need to be combined into sprites, you should begin creating a sprite (blank).

So, I analyze the site in the GTmetrix service and save it in turn separate folder on the computer, suggested images.

Save images in a separate folder

It is from these individual images that we will create a sprite.

Create a new image with a transparent background. Choose the size to fit all the images. Well, for example, if all your images are 32x32 and 16x16 pixels and there is one 380x150, then make your image so as to fit all these images in one.

And be sure to make a transparent background.

But even if you made a mistake with the size, you can always correct it through the menu item “Image” - “Image size”.

Now, one by one, display all the images that you prepared earlier.

Menu item “File” > “Open Image”. An image will open, select it CTRL+A and copy it to the clipboard CTRL+C. Go to the template and paste the image CTRL+V. And so with all the images.

It should look something like this.

Now you should cut off all the excess. To do this, use the Crop tool.

When the workpiece is ready, we save it in PNG format and half the job is done. Menu item “File” > “Save”. Don't forget about the format.

Now the image needs to be uploaded to the hosting in the folder with the theme images:

http://yourdomain/wp-content/themes/vahatema/images/

Please note that there may be differences in the name of the folder for storing theme images.

Uploading a file to your hosting can be done via file manager hosting, in my case it is . Or via . It's up to you.

Now comes the hard part, you need to replace the template images with a sprite. As an example, let’s take the block headers in the sitebar on my blog and examine the element code. To do this you need to click right button mouse on the desired element and in the context-sensitive menu select “View element code” (for Chrome) or “Examine element” (for Firefox). It's pretty much the same for other browsers.

Examining an element in a template

Here you can see the HTML code and CSS styles. That is, you see the file responsible for outputting styles and the line number where to look for the class responsible for this fragment. From the screenshot it is clear that the sidebar class and specifically the h2 header are located in the style.css file on line 339. This is where you need to enter everything necessary changes styles.

But already here in the element research window you can experiment with styles and choose the one you need. Then you just need to transfer these styles to the style.css file.

Before you start this step I highly recommend doing it backup copy style.css file.

Now your task is to open the style.css file and make the necessary changes. You can do this using Notepad++ (very convenient editor, and displays the line number) or through the editor in the WordPress admin panel.

So, let's open administrative panel WP– « Appearance» > "Editor" > "style.css". Since there is no line numbering here, you should look for the desired place using the search CTRL + F and enter the desired CSS class (in my case - sidebar h2).

Making changes to the style.css code

You just need to change the name of the image file and enter the position parameters relative to the coordinate axis. If yours is not like mine in the screenshot, then you should understand that the parameter is responsible for displaying the image (background): background: url(‘images/spriteme.png’);

And the parameter responsible for the position of the image is: background-position: -0px -0px; with negative values. The first number is the offset along the X axis, the second is the offset along the Y axis.

In this way you can replace many template images with one, the only difference will be in the position of this image. The work is very painstaking, but anyone can do it.

This completes the creation of CSS sprites for the site. Follow the instructions and you will succeed.

In the near future I will record a video tutorial in which I will try to show and talk in detail about creating CSS spryov.

And here is the promised video tutorial:

And a little cheat sheet css styles and lists used in the video tutorial, you can download the spur here.

That's all for me today. Friends, I wish you all good luck!

There are many methods for optimizing web pages. Some of them work, some don't. However, there are some methods that are mandatory for any website and blog. I wanted to talk to you about one of them.

One of the main methods for optimizing website pages. Therefore, today we will talk about how to combine image sprites on a website in CSS, thereby increasing their loading speed.

A little history

In the distant, distant past, when modems were beeping in apartments and connection speeds did not exceed 5 Kbps, people pored over the difficult task of how to make sites load faster without paying exorbitant sums for incoming traffic. They thought, that is, they thought, and they came up with the idea of ​​composing the images used on the page into sprites.

And away we go...

Combining images into a sprite

And so, as we previously found out, a sprite is several images arranged into one whole on transparent background, which can be accessed using CSS properties background-position. But please don't confuse it with a collage. Sprite ≠ collage.

In order to get a sprite, you need to fit all the buttons, icons, bullets and other crap as compactly as possible into one PNG file. Don't forget, the background must be transparent. Now let's look at it with an example.

Let's say we have PSD file Oh, with such a beautiful button in 3 states.

What does the average self-taught layout blogger do? It cuts out the button in each state and saves it in separate files. That is, one button takes 3 pictures from this nice man. And if you get stressed, remember that every picture on the site is an additional HTTP request that loads the server and your blog works slower and slower and slower and slower and slower and slower and slower...

To prevent this from happening, it is much more logical to save the button in one . To do this, we open the same PSD file, remove useless arrows, labels, and background from it and arrange all the button states as close to each other as possible without overlap.

This is what we ended up with. Under no circumstances should the buttons overlap each other.

Great, graphic file we have prepared it, now let me show you how to layout it.

Sprite layout

The layout of CSS sprites is no different from the layout ordinary pictures, with the exception of one BUT. You need to know not only the exact size of the image you want to display, but also its coordinates. For example, our entire sprite is 330 px wide and 150 px high.

But we only need to display a button that is 227 px wide and 41 px high, specifying its exact coordinates. If you don't have good html editor - I can.

Create a file index.html and write into it the necessary lines of code, doctype and all that.

After everything standard actions Done, let's try to display our button.

After tag body create a container div with class button– this will be our button.

1

This is where our html ends and now we need to add CSS styles for the button.

The code below shows that first we declare a class button. Then using properties height and width set the size of our button. Property background allows us to select the file that we will use as a sprite, and background-position set the coordinates of the image we need in this sprite. It's simple.

1 2 3 4 .button ( height : 41px ; width : 227px ; background : url (img/sprite.png ) ; background-position : 0px -12px ; )

Let's take a closer look at the property background-position.

As you can see from the code above, it has two meanings. The first value allows you to set the image coordinates along the X axis, and the second, therefore, along the Y axis. Our button does not jump anywhere along the X axis, since all states are located under each other. Therefore, in order for the second state of the button to appear on hover, we need to change the value responsible for the Y axis.

1 2 .button :hover ( background-position : 0px -56px ; ) .button :active ( background-position : 0px -98px ; )

As you know, and if not, then yes, each button has several states.

  • Normal – normal or normal state
  • Hover – button state when hovering the cursor
  • Active – button state when pressed
  • We took advantage of these properties.

    If you are too lazy to make sprites manually and generally bother with Photoshop, a wonderful free service: spritepad.wearekiss.com. Just throw it in work area the necessary pictures and he will create a sprite for you.

    In custody

    CSS sprites are very important stage on the way to speed up the site. Treat it with due respect and try to use it everywhere.

    Sprite ( computer graphics)

    Sprites in 2D graphics

    Initially, sprites meant small drawings that were displayed on the screen using hardware acceleration. On some machines (MSX 1, NES) software rendering led to certain restrictions, but hardware sprites did not have this limitation. Subsequently, with the increase in CPU power, hardware sprites were abandoned, and the concept of "sprite" was extended to all two-dimensional characters. In particular, in the video games Super Mario and Heroes of Might and Magic, all graphics are sprite-based.

    They returned to hardware-accelerated sprites in the mid-1990s, when the development of multimedia and the explosive increase in resolution and color depth required a specialized processor in the video card. It was then that DirectDraw was released as a wrapper over a 2D hardware accelerator. DirectX 8 introduced a common API for 2D and 3D graphics, and in modern sprite-based games, 2D sprites are rendered exactly like 3D sprites - as a textured rectangle.

    CSS sprites

    Used on the web. Several images are located in one graphic file. In order to cut the desired piece from a file, CSS is used - hence the name of the technology.

    CSS sprites save traffic and speed up loading - the browser will need to request fewer files.

    Sprites in 3D graphics First generation engines

    Firstly 3D games, such as Wolfenstein 3D () and Doom (), characters were represented as two-dimensional drawings that changed size depending on distance.

    On 3D accelerators

    3D accelerators use the following technique: the object is drawn as a plane with a texture with transparent areas superimposed on it. This technology is used in three cases.

    Optimization

    Sprites can be used for optimization graphics core, when rendering a three-dimensional detailed model is too expensive and can lead to a significant drop in rendering speed. These are:

    • Objects that are present in large numbers in the scene and which, being three-dimensional, would have a large number of edges and would greatly affect performance - for example, the audience (Fig. 1), grass, etc.
    • Distant objects that are drawn nearby by polygonal models.
    Special effects

    To make the image more believable, a large number of relatively small sprites (the so-called particle system) are used.

    Live shooting

    Occasionally, sprites are used to add live photos or videos to the game. For example:

    • Live actors, for example in realMyst (Fig. 4).
    • Control levers in simulators of planes, trains, etc., photographed in a real cockpit.

    It's worth noting that in some sprite-based games, such as Rise of the Triad, the sprites were photographed from actors rather than from models, toys, or drawings.

    The advent of shaders partially eliminates the need for live shooting - many of the nuances of a photographic image can already be conveyed by polygonal models in real time.

    Shattering the Illusion

    Viewing the sprite from an inappropriate angle will ruin the illusion. Depending on the mathematical rendering engine (“engine”), destruction can occur in two ways.

    Terminology
    • Billboard is a sprite constantly facing the camera (similar to billboards on highways, which are turned at the most favorable angle).
    • Impostor is a sprite that replaces a three-dimensional model at a great distance.

    Liked:
    27



    Disliked: 4

    No translation available.



    sprite

    before or after "before" "after" "after"

    angry_bird angry.png. index.html


    No translation available.


    CSS sprites are graphics for your Web site, combined into one graphic file. "Why one file?" - you ask. The fact is that this approach to storing images allows you to improve the performance of web pages, as well as store graphic images more organized. Let's take a look at some of the best practices using sprites. The very name of the sprites may remind you of gaming sprites, retro game console and even browser games that are so popular today:


    So, applicable to Web design, a sprite is just one big file, containing several images for your site, saving time for downloading and transferring the file over the network. When a sprite, for example, contains 20-30 images, this can significantly lighten the load on the server, since if these images were stored separately, the server would have to make 20-30 images accordingly individual requests to obtain each such image. Thanks to the sprite, only one HTTP request is sent to the server - to receive a single image. A sprite may not be visually “readable” to the eye, since its main task is only to assemble the different “pieces” of your design together. For example, a sprite could look like this:

    Sprites are used by most modern sites, and the well-known VKontakte is no exception. For example, this is how it stores “pieces” of the interface in one file - namely, familiar icons:

    The great thing about using CSS sprites is that you only need to send the server one graphic file containing all your images, rather than many individual images - and through CSS you can display any small segment of that graphic file as the background for an element. Some people think that individual images load faster, but this is not true. When loading one graphic file with many pictures, we send only one request to the server, and when loading large quantity pictures - we send more requests to the server. Combining images into one file can not only significantly reduce the number of HTTP requests, but also reduce overall size image file.

    Let me give you another example of a sprite. This is how one well-known Western website dedicated to design stores graphic elements:

    You may ask when in the best possible way prepare a sprite? There are two different approaches for this.

    Different approaches - creating a sprite before and after creating the site

    There are two common approaches when creating a sprite sheet - make it before or after creating your site. You can place all the images in a sprite sheet before creating the site. This is what we call the "before" approach. In addition, you can create all images as separate files, which makes editing them easier. Once the site is built and all the images are prepared, you can quickly and easily create a sprite sheet, either manually or using one of several tools. We will call this the “after” approach. If sprite sheets are new to you or you are new to Web design, then the “after” approach will be more suitable for you. There are many utilities, services and programs to help you create sprites, most of which are distributed and available for free.

    Arranging the pictures in the sprite in an organized manner

    When creating a sprite in Photoshop, it is advisable to immediately place all the images in an organized manner and in a certain sequence chosen by you, so that later working with them will be easy and simple. Try to always round the space for each sprite image to the nearest 10 pixels, or leave more space around them if they are all same size. When it comes to writing CSS styling, you won't have to write down coordinate measurements, and you'll be less likely to forget coordinate numbers required images. Here is an example of successfully placing different images in one sprite:

    From theory to practice! Create an animated bird from Angry Birds using a sprite

    So, we got acquainted with the concept of a sprite in Web design, but theory without practice is nothing. Therefore, now you and I will create our first sprite and learn how to make simple animation on the HTML page. Our example will be based on a character from the game Angry Birds - this is a funny red bird. First, let's prepare a sprite image in .PNG format containing 4 phases of bird animation:

    Let's create an angry_bird directory somewhere on the disk - we will place our example files there. We save the sprite with birds in this directory and call the file angry.png. Next step- create a file in the same directory named index.html - this will be our test page with animation. Next, open this file in the editor and place the following code there:


    Website lesson - Demonstration of working with sprites $(document).ready(function() ( // here will be the jQuery code that creates the animation ));


    Let me explain a little what we have done now. First, we set our HTML document to UTF-8 encoding, which means we must save our index.html in that encoding. You can also set another one, for example, windows-1251 - for our task this is not important. Next, we connected the style.css file to the document (it is not yet in our angry_bird directory, we will create it a little later). We have also provided a link to external script and connected jQuery library- With using jQuery We will dynamically change the pictures of our bird and change its “phases” from the sprite. We have also prepared an internal JavaScript block, where we will then place the code that animates the bird. And finally, the main body of the document contains a single hyperlink, inside which is a DIV block, and its ID is set to birdImage , and the default class is bird-sleeping . This means that our bird will be “sleeping” when opening the page - this corresponds to the lower left image inside the sprite - where its eyes are closed. Now is the time to “cut” our sprite, i.e. select individual images from it.

    Cutting a sprite using the SpriteCow.Com service

    The task of "slicing" a sprite is quite labor-intensive - it requires care in order not to make a mistake with the coordinates that define each image in the sprite. Fortunately, today there are services that completely remove this headache from the designer and layout designer. I use the service http://spritecow.com for slicing and recommend it to you. The essence of the service is simple and very convenient - we select each bird picture with the mouse, and SpriteCow gives us ready-made CSS code with coordinates. All we have to do is simply set 4 styles for each phase of the bird! Having entered the site, we see 2 buttons - “Open Image” and “Show Example”. We need the first button, click on it:

    In the dialog that opens, select our sprite file angry.png, after which we see how our sprite has been loaded onto the site. Next, we need to determine the background color, to do this, click on the “Pick Background” toolbar and point to the white area of ​​​​our sprite - this will allow us to correctly cut out each phase of the bird:

    Select the first image and automatically get the CSS code for it:

    Now, it's time to create a style.css file in our angry_bird directory. There we sequentially insert 4 generated pieces of CSS code, but instead of the standard .sprite class offered to us by SpriteCow, let’s call our styles more clearly. Also, since we store the sprite image directly in the root of the directory, we will remove the unnecessary path element - imgs/ from the background property. I got it like this:


    /* "regular" bird. Top left image in the sprite */ .bird-normal ( background: url("angry.png") no-repeat -12px -16px; width: 97px; height: 94px; ) /* "Happy" bird. Top right image in the sprite */ .bird-happy ( background: url("angry.png") no-repeat -118px -17px; width: 97px; height: 94px; ) /* "Sleeping" bird. Bottom left image in the sprite */ .bird-sleeping ( background: url("angry.png") no-repeat -12px -120px; width: 97px; height: 94px; ) /* "Angry" bird. Bottom right image in sprite */ .bird-angry ( background: url("angry.png") no-repeat -118px -120px; width: 97px; height: 94px; )


    The last step is to write the jQuery code that creates the animation.

    Now that we've successfully sliced ​​the sprite and placed 4 styles for each image in our style.css file, all we need to do is write some jQuery code that will add an animation when our hyperlink is hovered over and when the link is clicked. As we remember, by default we have the class bird-sleeping , i.e. our red bird will “sleep” when opening a document :)

    All animation will be based on 3 jQuery methods:

    • hover - handler for hovering the cursor over a link and for moving the cursor away from the link. When we hover the cursor, the bird will “wake up” - i.e. the class will become bird-normal
    • mousedown - handler for clicking the left mouse button on a link. In this case, the bird will become “happy” - i.e. The DIV block will be assigned the class bird-happy
    • mouseup - left mouse button release handler. When released, the bird will become "angry" - i.e. The DIV block is assigned the class bird-angry

    So, paste the following code into the place we prepared in indoor unit JavaScript placed on the page:


    $(document).ready(function() ( // here is the jQuery code that creates the animation $("#birdImage").hover(function() ( $(this).removeClass("bird-sleeping"); $ (this).removeClass("bird-angry"); $(this).removeClass("bird-happy"); $(this).addClass("bird-normal"), function() ( $(this) ).removeClass("bird-normal"); $(this).removeClass("bird-angry"); $(this).removeClass("bird-happy"); $(this).addClass("bird-sleeping" "); )); $("#birdImage").mousedown(function() ( $(this).removeClass("bird-sleeping"); $(this).removeClass("bird-normal"); $( this).removeClass("bird-angry"); $(this).addClass("bird-happy"); mouseup(function() ( $(this).removeClass("bird-sleeping"); $ (this).removeClass("bird-normal"); $(this).removeClass("bird-happy"); $(this).addClass("bird-angry" ));


    Ready! Testing animation

    OK it's all over Now! Our bird is ready and has brought life to the page with its animation! :) You can view the demo. Download the archive with an example at the bottom of the article.