gpt4 book ai didi

javascript - 为不同的桌面和移动 View 调整图像大小

转载 作者:行者123 更新时间:2023-11-30 16:10:13 25 4
gpt4 key购买 nike

我有一个结构,在两个 View 中,桌面 View 和移动 View 分别只有固定高度的图像,如下所示。

structure of images

在移动 View 中,图像会被拉伸(stretch)。我已经应用了几个解决方案,其中图像从顶部、底部、左侧和右侧被裁剪,在我的情况下我不想要。我应该如何操作才能使图像在任何 View 中都不会拉伸(stretch)?

最佳答案

假设你想要一个固定的布局(如你的图像),你可以使用 background-image/background-size 并像这样设置

background: url(...) no-repeat;        /* the shorthand property */
background-size: cover;
background-position: center center;

cover 值使图像始终填充元素而不拉伸(stretch)它,并且使用 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>

如果不想裁剪,可以使用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;
}
<div></div>
<div></div>
<div></div>

根据评论更新,在 img

上使用百分比高度(相对于主体)

html, body {
margin: 0;
height: 100%;
}
img {
height: 40%;
width: auto;
}
<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="">

关于javascript - 为不同的桌面和移动 View 调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36371783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com