可以用CSS设置背景图片的大小吗?
我想做一些类似的事情:
background: url('bg.gif') top repeat-y;
background-size: 490px;
但这样做似乎是完全错误的...
可以用CSS设置背景图片的大小吗?
我想做一些类似的事情:
background: url('bg.gif') top repeat-y;
background-size: 490px;
但这样做似乎是完全错误的...
如果需要将图像放大,则必须在图像编辑器中编辑图像本身.
如果你使用img标签,你可以改变大小,但是如果你需要图像作为其他内容的背景(并且它不会像你看起来想要的那样重复),那就不会给你想要的结果...
这可以在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
和contain
的值,它们给了我们新的控制力,这是我们以前没有的.
您也可以使用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;
}
这将调整图像宽度,使其在背景定位区域中多次匹配.
Additional note
If the size you need is static pixel size, it is still smart to physically resize the actual image. This is both to improve quality of the resize (given that your image software does a better job than the browsers), and to save bandwidth if the original image is larger than what to display.