图像100%的div

时间:2012-11-02 10:30:13

标签: javascript css image resize

如何将图像100%制作成div?

我有一个300x300的图像,我想把它变成一个更大的div的全尺寸。 (这个div的大小可以改变,所以我必须指定它的100%)

CSS或Javascript中是否有解决方案?

5 个答案:

答案 0 :(得分: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%;
}

答案 1 :(得分:2)

只需在图片代码中指定CSS样式width: 100%,即可覆盖其父容器的整个空间。

示例或jsFiddle

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

答案 2 :(得分:1)

  

<div style="width:450px;height:450px;">
      <img src="photo.png" style="width:100%;height:100%;"/>
  </div>

答案 3 :(得分: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。

小提琴here

答案 4 :(得分: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>​