How to make css sprites. Introduction to CSS Sprites for Dummies

On modern websites you can find a large number of graphics of various types: images of products, user avatars, pictures that form the design of pages, buttons, icons, logos, etc. And the larger the project, the more graphic files are used. When you open a separate page of the site in the browser, all its elements are loaded. Therefore, when there are too many graphics on it, loading speeds tend to slow down significantly. Which, in turn, is fraught with inconvenience for visitors to your project.

CSS Sprites

On the main page there is a form for uploading graphic files (for each file there is a separate button). Initially, only three download buttons are visible. If you need more, then click on “Need More”.

After all the files for the future CSS sprite are selected, click on the “Options” button. A small panel with settings will open in front of you. Here you can set the margins between elements in pixels, add a frame for images, align all pictures in the finished sprite to the left or top edge, and set the background color in RGB format.

After clicking on the “Generate” button, the CSS sprite will be directly created. You will also see small instructions for using it, namely the CSS code that you will need to place on your website. There is even an example in HTML. I don't think it's a problem to figure it out.

Visually, Dan’s Tools CSS Sprite Generator is a pretty nice CSS sprite generator with many settings. You can, for example, choose a vertical or horizontal type of insertion of icons into the overall image.

CSS Sprites

In the CSS Sprites service, everything is extremely simple both in design and settings. There is a choice of the resulting image format: PNG, JPEG, GIF. The page has a link to an adaptive version of sprite generation - Responsive CSS Sprites (although I have not tried it).

Total. In principle, we have considered all the nuances of how to make CSS sprites and use them. Generators will help speed up the process of creating elements, but you can get by with Photoshop. If you have any questions, write in the comments.

Sprites are a rather interesting and simple technology. Now I will tell you a little more about it.

What are CSS sprites?

In short, CSS sprites are several images in one file. There is one file, but there are several images inside it. At the same time, this is completely invisible to the visitor. To someone viewing the site, it seems that he sees several separate pictures.

Why is this necessary? Sprites reduce the number of page requests made by the user and reduce the overall size of images. As a result, the visitor will see the site faster.

How it's done? An ordinary picture increases in width and height, that is, several images are simply placed side by side on an ordinary picture. Then each individual image from this set is inserted into the desired block with a given width or height so that all other images are not visible. The entire set is cropped and only one picture remains. One sprite. All other pictures remain outside the specific block.

To make it clearer, I will give an analogy. Imagine that you are looking through a keyhole. You only see some separate piece of the room on the other side of the door. If you move a little to the side and look into the cave from a different angle, you will see some other piece of the same room.

Terminology

To avoid confusion, let's immediately define the terms:
Sprite- this is one picture from a file with several images.
Sprite set is the file itself with several images.

Features of using sprites

When should you use sprites? There is generally one answer - sprites should be used if you have a lot of small images on the page. It doesn't matter what kind of images they are. If you have a lot of gradients with the same location, a lot of buttons, a lot of icons, etc. If there are a lot of small images on a particular page, then you might consider using sprites.

There are usually three types of images on a page - jpg, png and gif. All these formats have two download modes - normal mode and gradual download mode.

The jpg format can be regular (basic) or progressive (progressive). In normal mode, the picture begins to be displayed line by line as it loads and immediately in good quality. In progressive mode, the jpg image is downloaded in its entirety at once, but in poor quality and the quality increases as it downloads.

Gif and png have the same behavior. GIF can be regular or interlaced. PNG can be regular or interlaced. The behavior of interlaced gifs and pngs is similar to that of progressive jpg. This behavior increases the file size slightly.

Total. The image may appear on the page immediately, or it may appear with a delay. This is important to know when it comes to sprites. It is advisable to make sprites interlaced or progressive. The user should see the pictures as quickly as possible, albeit in poor quality.

But! If the final file with all the sprites is too large, then despite all the progressiveness and interlacing, the visitor will have to wait even for a partial download of the file. Therefore, I don't recommend using large sets of sprites. If the file is large, then the whole point of sprites is completely lost - to speed up the site. With large sets of sprites, the user will have to wait as long, if not longer, than with regular split images.

Files over 30 kilobytes seem large to me. This is subjective. You may have your own ideas about the size of the file. A 30 kilobyte file will download in about 7 seconds with an internet speed of 56.6 kbps.

Examples of using sprites

Sprites with icons

In one sprite I will have icons for:

  1. List - one icon
  2. Links - three icons
  3. Search forms - one icon

That is, my first set of sprites will contain five pictures. All my pictures will be the same size - 16 by 16 pixels. Sprites can be used to create images with different resolutions; it is not necessary that the resolution of all images coincide. With different resolutions of pictures, it becomes a little more difficult to combine these pictures into one file.

As a result, the first example will look like this:

I found five icons. Then I simply combined them all in one file. This is the file I ended up with:

Draw your attention. In this case, the icons are not located closely, there are small indents between them. How to choose these indents? You can, of course, calculate everything pixel by pixel, but our case is quite simple, so here it is best to select these indents in the picture experimentally. First, we combine the images simply by eye, then we take the topmost picture and put it in the right place. If the picture is in its place, but at the same time a piece of another image sticks out from somewhere, then the indentation needs to be increased.

One more thing. The last icon in the list is the list icon - a green arrow. Why is she the last one? The location of the remaining icons in the picture is indifferent to us, but in the list any item can occupy several lines and if the green arrow is somewhere in the middle, then other pictures will stick out on the next lines. Look at the list picture above to see what I'm talking about.

So. I found five icons and combined them into one file. What do we do next? Of course we write the code:

  • List item
  • One more list item
  • List item
  • One more list item
    but in two lines
  • List item
  • One more list item

This is the html code for the list. Now let's apply our sprite to it:

Ul li( padding:0 0 0 21px; background:url("sprites.png") 0 -94px no-repeat; )

What have we done here? Indented each

  • 21 pixels from the left edge so that the text does not obscure the image. Then set sprites.png as the background image. The height of the entire picture with sprites in this case is 110 pixels and the green arrow is at the very end. The height of the green arrow is 16 pixels, that is, the arrow starts after the 94th pixel from the top of the picture. This means that we need to move the background 94 pixels up. In the CSS code it is written as “0 -94px”, that is, moved 0 pixels to the right and 94px pixels up.

    Let's finish with the list. Now let's make links in approximately the same way:

    A( padding:0 0 0 20px; background:url("sprites.png") 0 -42px no-repeat; ) a( padding:0 0 0 20px; background:url("sprites..png") 0 -21px no-repeat)

    What do the a selectors mean? Apparently this selector forces the browser to apply this style to all links that have an href attribute whose value begins with the string http://site/. The sprite itself is used in much the same way as in the case of a list. I will only consider one link - a link to my blog.

    1. We determine the required link by href.. You can simply assign a class to the desired link or add styles to the style attribute directly in the html code. Or identify the desired link using any other method.
    2. We make a margin of 20 pixels from the left edge of a specific link
    3. Specify the image sprites.png as the background image
    4. The image I chose for my blog is 21 pixels from the top edge, which means we need to move the background 21 pixels down. In css I wrote it like this: “0 -21px”

    Homework

    Sprites with gradients

    Now let's look at the second example.


    This picture shows a window. A window has a header, body and footer. Each of these elements has a background gradient set to it. Take a closer look, if it is not immediately visible, there is a color transition from pale to saturated.

    I'll show you how the gradients in this window can be made into sprites. The header and footer of the window will be a fixed height - 30 pixels. The window body will stretch depending on the length of the text.

    Now let’s write the html code for the window:

    Let's start using sprites. Let's start with the window title:

    #window-header( height:30px; background:#C0C0FF url("gradients.png") 0 0 repeat-x; )

    In the gradients.png file, first there is a gradient for the header, then for the body and then for the bottom line. That is, the gradient for the title starts from the very top. Therefore, we simply set the file itself as the background and indicate the position as “0 0”, that is, do not retreat anywhere. To make the gradient stretch horizontally, write “repeat-x”.

    To ensure that the entire gradient fits into the header, set the height to 30 pixels.

    Let's set a gradient for the footer in the same way as the header:

    #window-footer( height:30px; background: #C0FFC0 url("gradients.png") 0 -60px repeat-x; )

    Only this time we'll move the image down 60 pixels.

    The situation with the body of the window is more complicated. Our body will stretch, unlike the header and footer. That is, if we simply make one div for the window body and put a gradient there, then all the gradients will appear in this div at once. Alternatively, we can put the gradient for the body last vertically, but what if we have several gradients for blocks that stretch? You can’t do everything last at once. We'll do it a little more cleverly.

    The CSS code will be as follows:

    #window-body( position:relative; ) #window-body-gradient( position:absolute; left:0; top:0; width:100%; height:30px; background:url("gradients.png") 0 - 30px repeat-x; ) #window-body-text( position:relative; )

    Now I’ll tell you in more detail what we did here. Here is the html code of the window body separately:

    As you can see, we have two more divas embedded in the body. The first "window-body-gradient" will be responsible for the gradient. The second “window-body-text” is for text. In addition, as is clear from the CSS code, we applied position: relative; for the entire window body.

    For the gradient div we specify position:absolute. Thus, we knocked the gradient div out of the general flow. Now this div has no effect on anything. Since we have specified position: relative for the entire body, the gradient div does not float anywhere further than the parent. Attach it to the left and top edge of the window body using “left:0; top:0;". Set the height of the gradient div to 30 pixels. That is, here we indicate the height of the gradient that we will attach; if the height of the div is greater than the height of the gradient, then other sprites will stick out in the div. And finally, we attach our gradients.png file to the gradient div. As usual, we move the background up by the required distance; in this case, we move the background 30 pixels up.

    Now we have a gradient in the body of the window. But it obscures the text. To prevent the text from being obscured, we’ll wrap the entire text in a div and assign it position: relative. Once assigned, the text will be on top of the gradient.

    That's basically all. Now we have placed all the gradients in our window. And in the header, and in the body, and in the basement.

    I make such long explanations so that everything is completely clear. But in fact, if you know a little about layout, then it will probably be enough for you to look at the examples themselves:

    Once again I duplicated the link.

    In fact, you can come up with many examples of using sprites. I only showed two examples, but these examples should be enough to understand how sprites work. If you have any questions, ask in the comments.

    First, a short introduction. When loading a page, browsers are allowed only 2 requests to the server (in modern browsers this number has increased to 6). Each element of the site, be it a file with a style sheet, javascript files, pictures, are independent downloads that require a separate request to the server.

    There may be many thumbnails on the site. For example, emoticons, arrows, all kinds of small design elements. Each such image weighs negligibly little, but due to the huge number of requests, problems are created with the site’s loading speed.

    A long time ago (2003-2004), a solution to this situation was proposed with the main goal of speeding up site loading by reducing the number of requests to the server. This technology is called "Sprites".

    What are CSS sprites

    Sprite CSS- technology for combining small pictures into one. Using shifts via CSS, cutting out the desired part of the image is achieved

    For example, instead of 10 images, one is loaded, but larger. With proper distribution, this speeds up the site. However, the main thing here is not to overdo it. Combining images does not always give an advantage in loading a site.

    Example CSS Sprite

    Let's look at a small example of a CSS sprite implementation. Let's say we made the following picture from three separate arrows.

    To access the desired arrow in CSS you need to write

    This is what it looks like on the page:

    In the example considered, we used negative indents. This is done in order to raise the image up. For example, there is the following sprite:


    To cut the RSS icon we have to write the following indents

    background-position : -90px -40px ;


    In the example, we moved the image 40 pixels up and 90 pixels to the left.

    Pros of using sprites

    • Reducing the number of server calls
    • If dynamic changes to the image are used (for example, when hovering over a menu element), then the image will already be in the cache and therefore there will be no delay in loading at the right time
    • If the background of the combined images is similar, this will also reduce the total “weight” of the images

    Among the disadvantages of sprites: the complexity of the work in the case of manual labor. But fortunately, there are free services that are ready to simplify your work and do everything for you.

    In today's article I want to talk a little about CSS sprites and give some links where you can create these same sprites. The technique of using sprites is not new at all and has been used for a long time, but the complexity of their creation scares off webmasters. Let's try to help them...

    What are CSS sprites?

    Imagine one large picture that shows all your icons, dividers, buttons, arrows and other design components. It loads along with the site, everything is as usual. It just doesn’t create a bunch of requests for all files, but is executed with one request. Cool? Without a doubt. After loading, the desired part of the large image is displayed in the right place.

    I saw statistics somewhere (I don’t remember where, so I won’t give a link) - from 5 to 40% of the time it’s the pages themselves, the rest is the processing of requests by the server. It is logical to assume that if the number of requests decreases, the download speed will increase proportionally.

    Let's take a closer look at the pros and cons of using sprites:

    pros using sprites:

    Minuses these are technologies:

    • When laying out it is necessary to indicate not only the image, but also the position of the fragment, which is not entirely convenient and familiar.
    • increased load on the server. A large picture takes up more RAM, taking into account the “empties” between fragments.
    • To change one icon you will have to tinker with the entire file, which is not very convenient. Although, maybe it's for the better

    We choose what is more important to whom - simplicity or speed - and move on. If nothing can be done about the load on the server, then there are tools to solve problems with layout and changing sprites.

    Sprite generators— online services that, in principle, work according to the same scheme. You upload your set of images, select the sprite format, and the system creates the image and CSS markup for this file.

    Where to create sprites?

    Probably the oldest tool for creating CSS sprites. A distinctive feature is that there is a Russian version of the interface, which is convenient. It is highly customizable, not only the creation of the image, but also the CSS code. Overall - an excellent generator, I recommend it. By the way, in addition, the service can generate favicons and calculate access rights for Unix systems.

    CSS Sprites Generator

    This generator is also quite good, has all the necessary settings, and generates an output file of a slightly smaller size than the previous service. A distinctive feature is the convenient output of CSS code for each image.

    A fairly functional generator that allows you not only to create a regular sprite, it allows you to move pictures yourself, arranging them as compactly as possible. Plus - it can produce compressed CSS code, as well as SASS code.

    Sass is a CSS-based metalanguage designed to increase the level of abstraction of CSS code and simplify cascading style sheet files.

    This service differs from the others presented in that it does not create a sprite image. You can create it yourself in Photoshop or somewhere else, upload it here and the service will help with the CSS code. Quite clear and user-friendly interface. I recommend for those who like to do everything themselves, without trusting the machine

    A good generator, everything you need to create it is present. The only negative is that each image will have to be downloaded separately; you cannot download it in a bunch. Otherwise, nothing remarkable, solid average.

    The service is written in HTML5 and works only in Chrome and Firefox, but the development of such services is encouraging. The web does not stand still and that’s good. Very simple, minimal settings. But, if you want a quick and simple solution, this generator is 100% suitable

    Sprite generator for real Jedi Install the program, specify the path to the CSS file with the old layout and this service will do everything for you. It has a lot of capabilities - I recommend reading the documentation on the official website.

    Almost a complete analogue of Spritebox, it is also used only to obtain CSS code, with the difference that here the selection of the element’s border is carried out not manually, but automatically, the accuracy of the processing is noticeably higher. Works only in Chrome and Firefox

    An excellent service that works like this - go to a ready-made page, laid out as usual. Click on the service icon (you need to install it first with a bookmarklet) and that’s it - the service collects all the images from this page and generates a sprite with code. It’s very convenient, there are settings for exactly what needs to be put together. In general - a good service.

    A very simple, but understandable and convenient generator. Drag the pictures you want to combine, arrange them as you want and press the button - the sprite and code are ready. The downside of this service is that it only works in Chrome and Ognelis.

    The service is very similar to the SpriteMe described above, with the difference that here you need to manually upload all the images and the CSS file that needs to be changed. There are minimal settings, but it does its job well.

    I hope that now you are not afraid of working with CSS sprites and your projects will be even faster.

    Before CSS introduced the :hover pseudo-class, creating a rollover—an element that changes appearance when hovered over it—was implemented through JavaScript. Nowadays this is done much easier, but there is one drawback: if some background image should appear in the:hover state (i.e. when hovering the cursor over an element), then it begins to load at the moment the cursor is hovered, and not when the page is generally loaded .

    Because of this, there may be a slight delay when the picture appears for the first time. And although this delay no longer occurs with all subsequent cursor hovers, many developers have thought about how to fix this problem. For example, you can use JavaScript to ensure that all background images are loaded in advance. But there is a way that does not require knowledge of a programming language, and it is to use sprites.

    What are CSS sprites

    A CSS sprite is a single graphic file that contains many different images. It can contain, for example, all graphical interface elements, such as icons, buttons, etc. Also, sprites often combine background images along with their variations for the:hover state. Typical examples of sprites:

    A sprite that contains all the icons used. A sprite with social network icons and their variations for: hover

    Benefits of CSS Sprites

    • The CSS sprite contains background images for the various states of elements, and it is loaded in its entirety when the web page loads. This prevents the rollover from slowing down when you first hover over the element.
    • The number of calls to the server is reduced. After all, loading each small icon requires a separate request, and the fewer requests, the better. To download a sprite, you only need one request to the server.
    • Another advantage of storing many pictures in a sprite is that if they have a similar color palette, then one large image will weigh less than the individual small pictures combined.
    • All this generally has a positive effect on the site loading speed.

    How to create a sprite from pictures

    In the classic case, sprites are created in an image editor. Small pictures are sequentially placed on a large canvas (often with a transparent background), which is then saved as a graphic file.

    The manual method of creating sprites is quite a time-consuming task. Therefore, when the use of sprites began to gain momentum, online services for automatically creating sprite sheets appeared, for example, Spritegen, RetinaSpriteGenerator and others. You upload the necessary images in separate files to the site, and a sprite is generated for you, which you can immediately download to your computer.

    How to Use CSS Sprites

    Now it's time to learn how to use CSS sprites in practice. We'll show you a quick example using a sprite containing social media icons (we showed it above). In the normal state of the link, the social network icon will be colored (top row of the sprite), and when hovering the cursor it will turn gray (as in the bottom row).

    The HTML markup looks like this:

    We created our own class to link to each social network. Since this is a test example, we don't waste time filling out the href attributes - instead of links to real sites, we put placeholders. Inside the tag we do not place anything, because the appearance of the links will be determined by their background images with social network icons.

    Let's move on to CSS. First of all, let's write down general styles for all links:

    A ( background-image: url(https://goo.gl/1t18Rz); background-repeat: no-repeat; height: 98px; width: 100px; display: inline-block; margin-right: 10px; )

    The next two lines are the height and width of each element . How were these values ​​determined? Here we started from the size of the icons in the sprite. The height of each icon is 98 pixels and the width is 100 pixels. Next, we will position the background image for each link, adjusting the background so that the icon fits exactly into the link’s “window” of 98x100 pixels.

    A.facebook ( background-position: left top; )

    Let's go further: position the background for the Twitter link. The Twitter icon is positioned to the right of Facebook and flanks it without creating any empty spaces. We need to move the sprite to the left enough pixels to hide the Facebook icon and completely fill the link area with the Twitter icon. Since the width of each icon is 100 pixels, we shift the background to the left by 100 pixels. We are not changing the vertical positioning anywhere yet, but leaving the value top:

    A.twitter ( background-position: -100px top; )

    We will do a similar action for the remaining links, adding another 100 pixels to each subsequent horizontal positioning, thereby moving the sprite more and more to the left. You will get this picture:

    A.youtube ( background-position: -200px top; ) a.instagram ( background-position: -300px top; ) a.linkedin ( background-position: -400px top; ) a.tumblr ( background-position: -500px top ; ) a.google ( background-position: -600px top; )

    The result of this code is shown in the screenshot below:


    Now let's look at the behavior of background images when you hover over a link. We need to shift the sprite vertically upward so that the icon from the bottom row of the sprite falls into the viewing area. Everything here is quite simple and can be solved by one CSS rule, namely assigning the bottom value to the background-position-y property:

    A:hover ( background-position-y: bottom; )

    In our case, this style can be written one for all links, and it will work correctly. However, in other situations where the elements in the sprite are in a different order, you may need to write more code.

    See the demos below for the result of working sprites (to make the example more beautiful, we made the background shift smoother when hovering the cursor):


    If you were interested, here is the line that is responsible for the smooth change of icons (don’t worry, a little later we will study CSS animation, and in particular the transition property):

    A ( transition: all 0.2s ease-out; )

    So now you know what CSS sprites are and how they can be useful. In addition to preventing delays when loading background images, using sprites helps reduce the load on the server. In addition, this is a convenient way to store all graphical interface elements in one place.

    So we have looked at the main methods of link styling. We recommend that you practice further to consolidate your acquired knowledge. And the next chapter of our book is devoted to CSS animation, the implementation of which was made possible thanks to the properties that appeared in CSS3. And in the first lesson we will analyze the transformation property -