我如何让一个div自动调整到背景的大小,我为它没有设置一个特定的高度(或最低高度)?
当前回答
受到最受欢迎的答案的启发,我最终想出了一个使用min-height和“vw”单位的解决方案
我得到了一个比例非常不寻常的图像
通过我最终使用的实验
min-height: 36vw;
该值必须根据图像的比例变化
CSS代码使用在我的实际页面:
background:url('your-background-image-adress') center center no-repeat;
background-size: 100%;
background-position: top center;
margin-top: 50px;
width: 100%;
min-height: 36vw;
码笔示例https://codepen.io/viniciusrad/pen/GRNPXoL
其他回答
我敢肯定这东西在这里永远不会被看到。但如果你的问题和我一样,这就是我的解决方案
.imaged-container{
background-image:url('<%= asset_path("landing-page.png") %> ');
background-repeat: no-repeat;
background-size: 100%;
height: 65vw;
}
我想在图像的中心有一个div,这将允许我这样做。
有一种非常酷的方法可以让背景图像像img元素一样工作,这样它就可以自动调整它的高度。你需要知道图像的宽高比。将容器的高度设置为0,并根据图像比例将填充顶部设置为百分比。
它看起来如下所示:
div {
background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
background-size: contain;
background-repeat: no-repeat;
width: 100%;
height: 0;
padding-top: 66.64%; /* (img-height / img-width * container-width) */
/* (853 / 1280 * 100) */
}
你得到了一个具有自动高度的背景图像,这就像一个img元素一样。这是一个工作原型(你可以调整大小并检查div高度):http://jsfiddle.net/8m9ur5qj/
如果你在构建时知道图像的比例,想要基于窗口高度的高度,并且你可以针对现代浏览器(IE9+),那么你可以使用视口单元:
.width-ratio-of-height {
overflow-x: scroll;
height: 100vh;
width: 500vh; /* width here is 5x height */
background-image: url("http://placehold.it/5000x1000");
background-size: cover;
}
不完全是OP的要求,但可能很适合很多人看到这个问题,所以想在这里给出另一个选择。
小提琴:https://jsfiddle.net/6Lkzdnge/
我有这个问题,并找到了Hasanavi的答案,但我在宽屏上显示背景图像时遇到了一个小bug -背景图像没有扩散到屏幕的整个宽度。
所以这是我的解决方案-基于Hasanavi的代码,但更好…这应该适用于超宽屏幕和手机屏幕。
/*WIDE SCREEN SUPPORT*/
@media screen and (min-width: 769px) {
div {
background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
background-size: cover;
background-repeat: no-repeat;
width: 100%;
height: 0;
padding-top: 66.64%; /* (img-height / img-width * container-width) */
/* (853 / 1280 * 100) */
}
}
/*MOBILE SUPPORT*/
@media screen and (max-width: 768px) {
div {
background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
background-size: contain;
background-repeat: no-repeat;
width: 100%;
height: 0;
padding-top: 66.64%; /* (img-height / img-width * container-width) */
/* (853 / 1280 * 100) */
}
}
你可能已经注意到了,background-size: contains;属性不适合超宽屏幕,背景尺寸:覆盖;属性不适合移动屏幕,所以我使用这个@media属性来处理屏幕大小并修复这个问题。
在Umbraco CMS中有这个问题,在这种情况下,你可以使用div的'style'属性将图像添加到div:
style="background: url('@(image.mediaItem.Image.umbracoFile)') no-repeat scroll 0 0 transparent; height: @(image.mediaItem.Image.umbracoHeight)px"