html - 将 div 元素调整为其背景图像大小

标签 html css background

是否可以制作一个<div>适应它的背景图片?我的意思是保持宽度和高度的比例。

澄清:

  • div改变宽度。 (是响应式设计)

  • 我的意思不是让背景适应div。这可以通过 background-size 实现.但我要问的是绕过的方法:在背景中有一个图像,并使 div 父级适应该图像,无论其大小如何

  • 我知道如果我将图像放在 html 中而不是背景中,我可以做类似的事情。但在这种情况下,我无法针对不同的设备尺寸更改图像。所以我要求将图像放在背景中以便能够使用 CSS 更改它。

在我给出的例子中,我可以让图像适应宽度,但我得到了与高度的差距。当图像改变其大小时,我能否使 div 也适应图像的高度?换个方式问:在响应式环境下,有图片背景的div,可以变大不留空吗?

这里是 the example玩。

CSS:

#image {
    margin:0px auto; 
    width:90%;
    max-width:512px;
    height:512px; /* I need to give heigt to make it visible? */

    background-image:url('http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png');
    background-repeat:no-repeat;
    background-size:100%;
    background-color:yellow;/*just to make visible the gap in the height*/
}

HTML:

<div id="image"></div>

最佳答案

不可以使 div 适应它的背景图像。

因为它'毫无意义'

是这样的:

div 的大小由它的“内容”决定,或者它的尺寸是否被专门设置。 由于背景图像不属于这些类别中的任何一种,因此您可以看出这是不可能的。

你可以做的是:

HTML

<div class="image-controlled">
  <img>...</img>
  <div class="content">...</div>
</div>

CSS

 .image-controlled {
   position: relative; 
   overflow: hidden <-- optional, if you want to cut off .content which overflows the image boundaries
 }
 .content {
   position: absolute;
   top: 0; left: 0; <-- position of the content as it should be (normally)
 }

div 现在将是图像的大小,.content将显示在它上面。


另请注意 .content div 可以高于或低于 <img>按出现顺序排列,但效果是一样的。但是,如果您申请 position img 上的属性(property)元素,那么你需要设置 z-index.content大于<img>

关于html - 将 div 元素调整为其背景图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18297574/

相关文章:

css - 用作base-64背景图像数据时如何更改svg填充颜色?

java - 将 jInternalFrame 背景设置为透明

html - CSS/HTML 中几种不同的鼠标悬停字体颜色变化

javascript - 如何找到 DOM 元素的元素引用?

html - 无法将搜索元素保持在一条水平线上

javascript - 代码镜像 - 使给定行完全变灰

android - 在应用程序关闭时截取设备屏幕截图

php - 在 CSS 中调整图像大小

javascript - 未捕获的类型错误 : Cannot read property 'src' of undefined at displayFull

javascript - 将 HTML 添加到联系表单 7 提交电子邮件