CSS2和CSS3如何设置背景图片大小

CSS2

CSS2中如果需要将图像放大,必须修改使用图片编辑器修改图片本身。

如果使用img标签,可以通过width和height更改大小,但如果您需要将图像作为其他内容的背景,这个方法则不行。

CSS3

background-size是CSS3中一个可行的解决方案。

所有现代浏览器都支持这一点,所以除非您需要支持旧的浏览器,否则可以使用这个简便的方法。
支持浏览器:

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很容易跟cover属性混淆。

cover和contain比较

CSS2和CSS3如何设置背景图片大小 CSS2和CSS3如何设置背景图片大小

contain和cover都会保持纵横比。

可以看到contain在盒子的高宽比与图像不一致的时候造成了间隙。

而cover在盒子的高宽比与图像不一致的时候会造成剪切。

 


额外注意点

如果需要的大小是静态像素大小,那么对实际图像进行物理调整仍然是一个正确的选择

这既是为了提高调整大小的质量(假设图像软件比浏览器做得更好),也是为了节省带宽(如果原始图像比要显示的图像大)。

(0)
上一篇 2019年3月2日 下午10:33
下一篇 2019年3月5日 上午8:21

相关推荐

发表评论

登录后才能评论