将一个div元素的图像填充至100%。

3

如何让图片占据整个 div ?

我有一张 300x300 的图片,我想让它成为一个更大的 div 的全尺寸。(这个 div 的大小可能会改变,所以我必须在某个地方指定它的 100%)

在 CSS 或 Javascript 中有解决方案吗?


或者背景:url('链接')中心顶部不重复; 这将适合div。 - Vucko
我希望不要将其作为后台任务运行。但是下面的答案是解决方案。无论如何,谢谢 :) - Emilie
5个回答

2

试试这个:

<img src="test.jpg" alt="test" id="bg" />

img#bg {
  position:fixed;
  top:0;
  left:0;
  width:100%;
  height:100%;
}

CSS3也支持这个功能:

 #testbg{
background: url(bgimage.jpg) no-repeat;
background-size: 100%;
}

哇...我确信我已经尝试过这个了。好吧,它完美地工作了。谢谢! - Emilie

2

只需在图像标签中分配CSS样式width: 100%,即可使其覆盖其父容器的整个空间。

示例或jsFiddle

<div style="width: 500px;">
  <img src="yourPic.png" style="width: 100%" />
</div>

1
下面的 CSS 会缩放你的图片并填充 div 的 100% 宽度。
#imgId {
    width: 100%;
    height: auto;
}

但是如果您想要通过拉伸图像来填充整个 div,请使用

#imgId {
    width: 100%;
    height: 100%;
}

另一个有用的提示是,当您的宽度以百分比指定且您的图像是正方形时,可以采用此方法。

HTML

<div class="container">
    <img src="sample.jpg">
    <div style="clear:both;"></div>
</div>

CSS

.container {
    position: relative;
    width: 50%;
    height: 0;
    // % padding is calculated as % of width rather than height 
    // so height will equal 50%
    padding-bottom: 50%; 
}

img {
    position: relative;
    width: 100%;
    // image is square so as long as width is 100% then height will be the same.
    height: auto;
}
html, body {
    height: 100%;
    width: 100%;
}

以上意味着图像将始终调整大小以完全适应父div。
Fiddle here

1
尝试这个:http://jsfiddle.net/XUZV5/
<div style="height:100px;width:300px;">
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Mars-Schiaparelli.jpg/280px-Mars-Schiaparelli.jpg" style="width:100%;height:100px;"/>
</div>​

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接