我有一个结构,在这两个视图中,桌面视图和移动视图都只有像下面这样的图像。
在移动视图中,图像会拉长。 我已经应用了几个解决方案,其中图像从顶部,底部,左侧和右侧裁剪,在我的情况下我不想要。 我应该如何处理图像不会在任何视图中拉伸?
答案 0 :(得分:2)
假设您想要一个固定的布局(如图片中所示),您可以使用background-image
/ background-size
并将其设置为
background: url(...) no-repeat; /* the shorthand property */
background-size: cover;
background-position: center center;
cover
值使图片始终填充元素而不拉伸它,使用background-position
可以控制图像是居中,左,右,下,上对齐
div {
height: 200px;
width: 500px;
background: url(http://lorempixel.com/300/400/animals/4) no-repeat;
background-size: cover;
background-position: center center;
border: 1px solid black;
}
div ~ div {
height: 200px;
width: 200px;
}
div ~ div ~ div {
height: 500px;
width: 200px;
background-position: left center;
}

<div></div>
<div></div>
<div></div>
&#13;
如果您不想裁剪,可以改用background-size: contain
。
div {
height: 200px;
width: 500px;
background: url(http://lorempixel.com/300/400/animals/4) no-repeat;
background-size: contain;
background-position: left bottom;
border: 1px solid black;
}
div ~ div {
height: 200px;
width: 200px;
}
div ~ div ~ div {
height: 500px;
width: 200px;
}
&#13;
<div></div>
<div></div>
<div></div>
&#13;
根据评论进行更新,使用img
html, body {
margin: 0;
height: 100%;
}
img {
height: 40%;
width: auto;
}
&#13;
<img src="http://lorempixel.com/200/400/animals/4" alt="">
<img src="http://lorempixel.com/300/300/animals/4" alt="">
<img src="http://lorempixel.com/400/200/animals/4" alt="">
&#13;