我如何让一个div自动调整到背景的大小,我为它没有设置一个特定的高度(或最低高度)?


当前回答

在Umbraco CMS中有这个问题,在这种情况下,你可以使用div的'style'属性将图像添加到div:

style="background: url('@(image.mediaItem.Image.umbracoFile)') no-repeat scroll 0 0 transparent; height: @(image.mediaItem.Image.umbracoHeight)px"

其他回答

也许这有帮助,这不是一个确切的背景,但你能理解:

<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>

添加到div

style="overflow:hidden;"

我能想到的最好的解决办法是用百分比来指定你的宽度和高度。这将允许您根据显示器大小调整屏幕大小。它更响应式的布局。

举个例子。 你有

<br/>
<div> . //This you set the width percent to %100
    <div> //This you set the width percent to any amount . if you put it by 50% , it will be half
    </div>
 </div>

这是最好的选择,如果你想要一个响应式布局,我不建议浮动,在某些情况下浮动是可以使用的。但在大多数情况下,我们避免使用float,因为当你进行跨浏览器测试时,它会影响很多事情。

希望这对你有所帮助。

这个答案与其他答案相似,但对于大多数应用程序来说是最好的。你需要事先知道你通常做的图像大小。这将允许您添加叠加文本,标题等,没有负填充或绝对定位的图像。关键是设置填充%以匹配图像纵横比,如下面的例子所示。我使用了这个答案,本质上只是添加了一个图像背景。

.wrapper { width: 100%; /* whatever width you want */ display: inline-block; position: relative; background-size: contain; background: url('https://upload.wikimedia.org/wikipedia/en/thumb/6/67/Wiki-llama.jpg/1600px-Wiki-llama.jpg') top center no-repeat; margin: 0 auto; } .wrapper:after { padding-top: 75%; /* this llama image is 800x600 so set the padding top % to match 600/800 = .75 */ display: block; content: ''; } .main { position: absolute; top: 0; bottom: 0; right: 0; left: 0; color: black; text-align: center; margin-top: 5%; } <div class="wrapper"> <div class="main"> This is where your overlay content goes, titles, text, buttons, etc. </div> </div>

有一个纯CSS的解决方案,其他的答案错过了。

“content:”属性主要用于在元素中插入文本内容,但也可以用于插入图像内容。

.my-div:before {
    content: url("image.png");
}

这将导致div将其高度调整为图像的实际像素大小。要调整宽度,添加:

.my-div {
    display: inline-block;
}