我如何让一个div自动调整到背景的大小,我为它没有设置一个特定的高度(或最低高度)?
当前回答
假设你有这样的东西:
<div class="content">
... // inner HTML
</div>
你想给它添加一个背景,但你不知道图像的尺寸。
我也遇到过类似的问题,我用网格解决了它:
HTML
<div class="outer">
<div class="content">
... // inner HTML
</div>
<img class="background" />
</div>
CSS
.outer{
display: grid;
grid-template: auto / auto;
// or you can assign a name for this block
}
.content{
grid-area: 1 / 1 / 2 / 2;
z-index: 2;
}
.background{
grid-area: 1 / 1 / 2 / 2;
z-index: 1;
}
z索引是用来放置背景图像的,你当然可以放置img。div.content上面的背景。
注意:这可能会导致div.content具有与图片相同的高度,所以如果div.content有任何根据其高度放置的子元素,你可能想要设置一个数字,而不是像'auto'这样的东西。
其他回答
有一个纯CSS的解决方案,其他的答案错过了。
“content:”属性主要用于在元素中插入文本内容,但也可以用于插入图像内容。
.my-div:before {
content: url("image.png");
}
这将导致div将其高度调整为图像的实际像素大小。要调整宽度,添加:
.my-div {
display: inline-block;
}
也许这有帮助,这不是一个确切的背景,但你能理解:
<style>
div {
float: left;
position: relative;
}
div img {
position: relative;
}
div div {
position: absolute;
top:0;
left:0;
}
</style>
<div>
<img src="http://antwrp.gsfc.nasa.gov/apod/image/0903/omegacen_davis.jpg" />
<div>Hi there</div>
</div>
这可能会有帮助,这不是一个确切的背景,但你明白这个简单的想法吗
<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>
受到最受欢迎的答案的启发,我最终想出了一个使用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
没有办法使用CSS自动调整背景图像大小。
正如其他人所提到的,您可以通过测量服务器上的背景图像,然后将这些属性应用到div来解决这个问题。
你也可以修改一些javascript来根据图片大小调整div的大小(一旦图片已经下载)——这基本上是一样的事情。
如果你需要你的div自动适应图像,我可能会问你为什么不放一个<img>标签在你的div?