Azeem Haider
Azeem Haider

Reputation: 111

Stretch a part of background image

I have an image which holds multiple flag images:

Flags

I have a div which has the dimensions: width:100px; height:50px. I want to stretch each flag to fit into it:

.flag{
      width:100px;
      height:50px;
      background-image: url('http://icons.iconarchive.com/icons/famfamfam/flag/icons-390.jpg');
      background-position: 30px 25px;
      background-size: 390px 260px; // actual size of image
    }
<div class="flag"></div>

Upvotes: 1

Views: 504

Answers (2)

xpy
xpy

Reputation: 5641

Since your flag size is 16x11px and you want to present it as 100x50px, you will have to scale your image 100/16 = 6.25 times on the x axis and 50/11 = 4.54 times on the y axis. So you will have:

background-size: calc( 390px * 6.25 ) calc ( 260px * 4.54 );

Of course that means that you will also have to calculate the background-position accordingly. So, for the first flag we'll have:

.flag {
  width: 100px;
  height: 50px;
  background-image: url('http://icons.iconarchive.com/icons/famfamfam/flag/icons-390.jpg');
  background-position: -38px -36px;
  background-size: calc(390px * 6.25) calc(260px * 4.5); // actual size of image
}
<div class="flag"></div>

Which, of course, looks lame but that always happens with stretched images.

Now, if you are really into it, you can use the image-rendering property to "fix a little" the rendering for FireFox and Chrome.

.flag {
  width: 100px;
  height: 50px;
  background-image: url('http://icons.iconarchive.com/icons/famfamfam/flag/icons-390.jpg');
  background-position: -38px -36px;
  background-size: calc(390px * 6.25) calc(260px * 4.5);
  image-rendering: -moz-crisp-edges;
  image-rendering: pixelated;
}
<div class="flag"></div>

Upvotes: 2

ScaisEdge
ScaisEdge

Reputation: 133410

use no repeat

<div class="flag"></div>


//Style
.flag{
   width:100px;
   height:50px;
   background-image: url('http://icons.iconarchive.com/icons/famfamfam/flag/icons-390.jpg');
   background-position-x: 30px;
   background-position-y: 25px;
   background-size: 390px 260px; // actual size of image
   background-repeat: no-repeat;
}

Upvotes: 0

Related Questions