一、图片宽度控制基础
width
: 设置图片的宽度。height
: 设置图片的高度。max-width
: 设置图片的最大宽度。max-height
: 设置图片的最大高度。
1.1 固定宽度
img {
width: 200px;
}
1.2 固定高度
img {
height: 150px;
}
1.3 最大宽度
img {
max-width: 300px;
}
1.4 最大高度
img {
max-height: 200px;
}
二、防止图片变形
2.1 使用object-fit
object-fit
属性可以控制替换元素(如img
、video
等)的内容如何适应其尺寸框。以下是一些常用的值:
fill
: 填充整个框,可能失真。contain
: 保持宽高比,可能留下空白。cover
: 保持宽高比,填充整个框。scale-down
: 与cover
类似,但只在需要时缩放。
例如:
img {
object-fit: cover;
max-width: 100%;
height: auto;
}
2.2 使用background-size
cover
: 保持宽高比,填充整个框。contain
: 保持宽高比,可能留下空白。initial
: 使用元素的初始值。inherit
: 继承父元素的值。
例如:
.div {
background-image: url('image.jpg');
background-size: cover;
}
2.3 使用padding-top
.div {
position: relative;
width: 100%;
padding-top: 56.25%; /* 16:9宽高比的容器 */
}
.div img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: auto;
}
三、图片宽度自适应
3.1 使用width: 100%
img {
width: 100%;
height: auto;
}
3.2 使用max-width: 100%
img {
max-width: 100%;
height: auto;
}
3.3 使用object-fit: cover
img {
object-fit: cover;
max-width: 100%;
height: auto;
}