.img-responsive
is better not to use here - this bootstrap class is not combined with css sprites. Because it directly affects the image, and here it is necessary to influence its parent (you have this .photo
).
The layout will be as follows:
<div class="photo photo_4"> <div class="photo__item photo__item_4"></div> </div>
Pay attention to photo_4
and photo_item_4
- these classes are needed to stylize a separate image of the sprite.
For tests, I took this one sprite , a working example is available here: https://jsfiddle.net/gambala/72Let9a4/
.photo
we adjust to the entire width of the container:
.photo { width: 100%; }
At the same time .photo_4
we limit the width:
.photo_4 { max-width: 112px; }
Where 112px
is the width of a single image in the sprite. Note the value in pixels.
Next - the styles of the image itself:
.photo__item { background-repeat: no-repeat; padding-bottom: 100%; width: 100%; }
width: 100%
stretches the image on the parent, that is, on .photo
. But, since .photo
limit of 112px
- the image will no longer stretch at this point.
padding-bottom: 100%;
- an important attribute. Our image has a height of zero, but there is a bottom padding equal to the width of the .photo
container. As a result, the actual height of our image will be equal to its width, including in the case of 112px
. We get a rubber square. In it, we will put the background sprite.
If your image in the sprite is not square - then your padding-bottom
will be different. For example, if the image is 112px*83px
, then the padding-bottom
will be 83px / 112px = 0.7410 = 74.10%
When we put an image as a background - we indicate all the dimensions as a percentage :
.photo__item_4 { background: #fff url("https://cdn.tutsplus.com/webdesign/uploads/legacy/tuts/373_sprites/angry_birds.png"); background-position: 0 38.88%; background-size: 535.71% 357.14%; }
Formula calculation:
- Size in width -
600px / 112px = 5.3571 = 535.71%
- The size in height is
400px / 112px = 3.5714 = 357.14%
- Indent on X -
0px / ( 600px - 112px ) = 0
- The indent is
112px / ( 400px - 112px ) = 0.3888 = 38.88%
Where:
600px
- sprite width400px
- sprite height112px
in size, as well as inside the brackets in the indent - the width and height of the image in the sprite0px
and 112px
in indents - image indent in sprite on X and Y
Working example: https://jsfiddle.net/gambala/72Let9a4/