use*_*590 2 html css image viewport css3
我有3种不同的盒子尺寸,我需要在其中显示图像.图像应占据盒子的整个宽度和高度,但不应拉伸.它可以裁剪和居中图像.
这是一个例子:https: //jsfiddle.net/y1zn0mxy/
如果您看到3种不同的尺寸,您将看到它在第一种和第二种情况下有效但在最后一种情况下不起作用.如果我将图像标签的大小交换为:它将在最后一个中工作:
width: 100%;
height: auto;
Run Code Online (Sandbox Code Playgroud)
但是它在前两个版本中不起作用.
有没有其他方法来实现这一目标
您可以通过将图像作为背景图像而不是<img />标记插入来实现所需的效果.优点是,您不需要应用图像标记和CSS.只需使用background-size: cover;始终使图像适合视口.这样,您可以使用更少的代码并通过CSS 后台属性控制图像.
.img {
background-image: url(http://i.kinja-img.com/gawker-media/image/upload/jour87ix9aoikm1zpjct.jpg);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}Run Code Online (Sandbox Code Playgroud)
<div style="width:300px; height:250px; margin: 30px; background: black; float: left;">
<div class="img box" style="padding:0; width: inherit; height: inherit;"></div>
</div>
<div style="width:300px; height:500px; margin: 30px; background: black; float: left;">
<div class="img box" style="padding:0; width: inherit; height: inherit;"></div>
</div>
<div style="width:500px; height:200px; margin: 30px; background: black; float: left;">
<div class="img box" style="padding:0; width: inherit; height: inherit;"></div>
</div>Run Code Online (Sandbox Code Playgroud)