背景尺寸:包含 [英] Background size : contain
问题描述
我想要一个div与背景图像保持图像的高宽比,固定的高度为500px,我想在该div的背景上没有padding。
这是可能吗?
我可以得到一个固定高度的div和一个保持宽高比的背景图像:
< div style =background:url(something.png)50%50%/ cover#D6D6D6; background-size:contains; background-repeat :no-repeat; height:500px>< / div>
这使得图像居中在div的中间(垂直或水平),但给出一些填充到背景的div ...
有人可以帮助我吗?
您尝试实现的是仅使用CSS无法实现的,您可以使用JavaScript来检测图像的宽度,然后将 div
的宽度设置为相同。或者,您可以简单地删除 background-image
属性,而将图像作为 img
标记添加到HTML中。如果你这样做,你可以显示 div
作为 inline-block
这将照顾使<$ c $
body {text-align:center;} div {background-color:#666; display:inline-block;} div img {height:500px;}
< div> < img src =http://lorempixel.com/200/500alt =>< / div>
>
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 ?
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>
这篇关于背景尺寸:包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!