I have a png image which has transparent space around the actual image.
like this
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 class="borderDiv">
<div class="imgBck">
</div>
</div>
2
Answers
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
andbackground-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:The aspect ratio of the containing
div
is equal to the aspect ratio of the image => 300×200 (fixed ‘px’ units) and 800×600 (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 be1.125:1
, orwidth: 225px; height: 200px
.Once this has been established, you can use
background-position
andbackground-size
to resize thebackground-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