如何让放置在 div 内的图片填满整个 div?

8

目前我正在使用这段代码:

<style type="text/css">
   .icondiv{
      border:1px solid;
      content: url(image.png) 100% 100%;
   }
</style>

<div class="icondiv"></div>

输出效果是这样的,图片停留在div的1/4位置。我该如何使图片填满整个div?我已经检查过图片,没有多余的空白。

3
这里似乎有一个错误...也许你想要使用 background: url() no-repeat center center; background-size: cover; - Luís P. A.
Luis,你应该将其添加为答案。 - Devin H.
6个回答

10

如果您不想使用背景图片

.container{
  width: 400px;
  height: 100px;
}
.container img{
  width: 100%;
  height: auto;
}
@supports(object-fit: cover){
    .container img{
      height: 100%;
      object-fit: cover;
      object-position: center center;
    }
}
<div class="container">
  <img src="http://i62.tinypic.com/2dh8y1g.jpg" alt="" />
</div>

但要注意支持情况:http://caniuse.com/#search=object-fit


1

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}
.icondiv {
    width: 400px;
    height: 100px;
    border: 1px solid #f00;
    position: relative;
}
.icondiv img {
    position: absolute; top: 0; left: 0;
    width: 100%;
    height: 100%;
}
<div class="icondiv">
    <img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSL19OsbasMqU64_o3uoov5liyKmD8KMStU1OR8hXUtV4pwALr7Sg" alt="" />
</div>


0

看起来你正在尝试使用CSS将图像添加到div中,而不是在HTML中进行内联...我会假设你有充分的理由这样做并效仿。你可以使用背景将图像放入其中,并使其扩展以填充容器,而不是使用“content:”。

.container {
    width: 700px;
    height: 400px;
    background:#f00 url(http://i48.tinypic.com/wrltuc.jpg) no-repeat center center;
    background-size:cover;
    margin: 0 auto;
    border: solid black 1px;
}
<div class="container">
</div>

使用“background-size:cover”技术的好处是,您的图像将始终填充包含div,而不管其比例如何。

0
你应该使用
<div class="container">
 <img src="http://i48.tinypic.com/wrltuc.jpg" />
</div>

.container {
    width: 700px;
    height: 400px;
    background: #444;
    margin: 0 auto;
    border: solid black 1px;
}
.container img{
    width: 100%;
    height: 100%;
}

在这里试试 Fiddle


0

试试这个:

.icondiv{
  border:1px solid;
  background: url(yourimage.png) no-repeat center center;
  background-size: cover;
  width: 200px; // Adjust your needs
  height: 200px; // Adjust your needs
}

0
你可以创建一些类似这样的 CSS 类:
full {
  background-image: url(image_path('yourimage.jpg'));
  background-repeat: no-repeat;
  background-position:  center;
  background-attachment: fixed;
  background-size: cover;
}

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