Reputation: 149
I would like a div with a background-image that keeps the aspect ratio of the image, with a fixed height of 500px and i want no "padding" on the background of that div. Is this possible to do?
I Can get a div with a fixed height and a background-image that keeps aspect ratio :
<div style="background: url(something.png) 50% 50% / cover #D6D6D6;background-size: contain;background-repeat: no-repeat;height:500px"></div>
This makes the image centered in the middle of the div ( either vertically or horizontally ) but gives some padding to the background of the div ...
Can anybody help me out ?
Upvotes: 0
Views: 818
Reputation: 67748
background-size: contain;
will always display the whole image (without cutting off anything), thereby leaving some space either vertically or horizontally.
On the other hand, background-size: cover;
will fill the whole DIV in a way that the shorter side of the image corresponds exactly to the length or height of the DIV (depending on the relation of the proportions between DIV and image) and the longer one is cut off on the sides or on top and bottom.
If you don't want a distorted image, those are the options you have.
Upvotes: 1
Reputation: 6233
What you are trying to achieve is not possible using only CSS, you could use JavaScript to detect the width of the image and then set the width of the div
to be the same. Or alternatively you could simply remove the background-image
property and rather add the image as an img
tag into your HTML. If you do that you can display the div
as inline-block
which will take care of making the div
as wide as the width of the image.
body
{
text-align:center;
}
div
{
background-color:#666;
display:inline-block;
}
div img
{
height:500px;
}
<div>
<img src="http://lorempixel.com/200/500" alt="">
</div>
Upvotes: 2