⬆️ ⬇️

Down with the absolute units in the icons, sprites



Sprites - a cool way to reduce the number of requests to the server. You can pack a bunch of icons in one sprite and write in CSS offsets for each icon. However, it is very inconvenient that you need to take all this for a pixel by pixel. Pixels mean no dynamics. If you use pixels, then a piece of the sprite will be displayed in a fixed size - regardless of whether it is displayed inside the paragraph, or inside the title. This is wrong, it seems to me, and uncomfortable. But it seems that I have found an interesting way to display icons of dynamic size.



First of all, you need to stop thinking about sprite, as things with width and height expressed in pixels. The sprite on the picture in the header is 500 by 100 pixels, but it should be perceived as a sprite, which has a size of 10x2. In fact, what's the difference how many pixels does he have? The main thing is that it contains 10 icons in width and two in height.



During the layout of the description of the sprite just need to specify the width and height of the background image in relative units - I will use EM. Since the sprite has a size of 10 by 2, it can be described as:



.icon { background-image: url(http://i.imgur.com/DV0Bl7B.png); display: inline-block; /*  — 10,  — 2. */ background-size: 10em 2em; /*   11 —   ,    */ width: 1em; height: 1em; } /*  .        */ .icon-ok-black { background-position: -7em -1em; } 


')

Due to the fact that all sizes are specified in relative units, the icon will automatically adjust to the font size - in the title it will correspond to the font size of the title, in the paragraph - the size of the paragraph font, and so on. You can make one sprite, for example, with the size of each icon at 50 pixels, and these 50 pixels will always scale to the size of 1em in the current context.



However, keep in mind that when scaling bitmap graphics may be blurred. Perhaps this method is best suited for vector graphics — SVG, for example. Thanks to BaNru for a valuable comment.



JSFiddle example: jsfiddle.net/vdfqdfen

Source: https://habr.com/ru/post/245331/



All Articles