Home > Mobile >  Setting png image as a div background
Setting png image as a div background

Time:02-02

I have a png image which has transparent space around the actual image.

like this

png image

I want to place this image as a background for a div. But the div should only display the image without the transparent area around it.

This is what I have now. https://jsfiddle.net/qhoty913/8/

How can I make sure that the inner div image starts from the actual image and it wont have the blank spaces around it. Is it possible without modifying the actual png image file?

.imgBck {
  margin: 10px;
  width: 300px;
  height: 200px;
  background-image: url('https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png');
  background-size: cover;
  border-style: dotted;
}

.borderDiv {
  border-style: solid
}
<div >
  <div >
  </div>
</div>

CodePudding user response:

In order to remove the blank spaces around it, you should remove the margin you have added. In addition to that, I am not sure what you mean with your question, but you can try playing around with the background-size and background-position properties to make the image look the way you like. I played around with the code a bit, and came up with this simple fix, yet I am not completely sure if this is what you are looking for. By making the divs more fluid, you can get rid of the transparent spaces you are mentioning:

.imgBck {
  width: 100%;
  height: 200px;
  background-image: url('https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png');
  background-position: 10px;
  background-size: cover;
}

.borderDiv {
  border-style: solid
}
<div >
  <div >
  </div>
</div>

CodePudding user response:

The aspect ratio of the containing div is equal to the aspect ratio of the image => 300x200 (fixed 'px' units) and 800x600 (image physical size) => aspect ratio: 3:2. Therefore, you cannot resize the background to 'lose' the excess space without cutting parts of the cubes or get some unwanted width vs. height stretching.

This is due to the fact that to lose excess space, the actual aspect ratio of the containing div has to be 1.125:1, or width: 225px; height: 200px. Once this has been established, you can use background-position and background-size to resize the background-image and lose the excess space.

Please be aware that this method is very image specific and proper cropping of a single background image is likely the preferred method.

snippet

.imgBck {
  margin:  10px;
  width : 225px; /* from 300px */
  height: 200px;

  background-image   : url('https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png');
  background-position: 47% 20%; /* ADDED */
  background-size    : 140%;    /* from 'cover' */
  background-repeat  : no-repeat;

  border-style: dotted;
}
.borderDiv {
  border-style: solid
}
<div >
  <div >
  </div>
</div>

  • Related