我如何让一个div自动调整到背景的大小,我为它没有设置一个特定的高度(或最低高度)?
当前回答
这个怎么样?
.fixed-centered-covers-entire-page { 保证金:汽车; 背景图片:url (https://i.imgur.com/Ljd0YBi.jpg); 平铺方式:不再重演;background-size:封面; 背景位置:50%; background - color: # fff; 左:0; 右:0; 上图:0; 底部:0; z - index: 1; 位置:固定; } < div class = " fixed-centered-covers-entire-page " > < / div >
演示:http://jsfiddle.net/josephmcasey/KhPaF/
其他回答
受到最受欢迎的答案的启发,我最终想出了一个使用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
有一种非常酷的方法可以让背景图像像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/
有一个纯CSS的解决方案,其他的答案错过了。
“content:”属性主要用于在元素中插入文本内容,但也可以用于插入图像内容。
.my-div:before {
content: url("image.png");
}
这将导致div将其高度调整为图像的实际像素大小。要调整宽度,添加:
.my-div {
display: inline-block;
}
如果你在构建时知道图像的比例,想要基于窗口高度的高度,并且你可以针对现代浏览器(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/
这可能会有帮助,这不是一个确切的背景,但你明白这个简单的想法吗
<style>
div {
float: left;
position: relative;
}
div img {
position: relative;
}
div div {
position: absolute;
top:0;
left:0;
}
</style>
<div>
<img src="http://www.planwallpaper.com/static/images/recycled_texture_background_by_sandeep_m-d6aeau9_PZ9chud.jpg" />
<div>Hello</div>
</div>