CSS2
如果需要放大图像,则必须在图像编辑器中编辑图像本身。
如果您使用 img 标签,您可以更改大小,但是如果您需要图像作为其他内容的背景(并且它不会像您似乎想要的那样重复自身),那么这不会给您带来所需的结果...
CSS3 unleash the powers
这可以在 CSS3 中做到background-size
.
All modern browsers support this, so unless you need to support old browsers, this is the way to do it.
Supported browsers:
Mozilla Firefox 4.0+ (Gecko 2.0+), Microsoft Internet Explorer 9.0+, Opera 10.0+, Safari 4.1+ (webkit 532) and Chrome 3.0+.
.stretch{
/* Will stretch to specified width/height */
background-size: 200px 150px;
}
.stretch-content{
/* Will stretch to width/height of element */
background-size: 100% 100%;
}
.resize-width{
/* width: 150px, height: auto to retain aspect ratio */
background-size: 150px Auto;
}
.resize-height{
/* height: 150px, width: auto to retain aspect ratio */
background-size: Auto 150px;
}
.resize-fill-and-clip{
/* Resize to fill and retain aspect ratio.
Will cause clipping if aspect ratio of box is different from image. */
background-size: cover;
}
.resize-best-fit{
/* Resize to best fit and retain aspect ratio.
Will cause gap if aspect ratio of box is different from image. */
background-size: contain;
}
我特别喜欢的是cover
and contain
这些价值观赋予我们前所未有的新控制力。
Round
您还可以使用background-size: round
与 Repeat 结合使用时有意义:
.resize-best-fit-in-repeat{
/* Resize to best fit in a whole number of times in x-direction */
background-size: round auto; /* Height: auto is to keep aspect ratio */
background-repeat: repeat;
}
这将调整图像宽度,使其适合背景定位区域的整数次。
附加说明
如果您需要的大小是静态像素大小,则物理调整实际图像的大小仍然是明智的。这既是为了提高调整大小的质量(假设您的图像软件比浏览器做得更好),也是为了在原始图像大于要显示的图像时节省带宽。