Code前端首页关于Code前端联系我们

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

terry 2年前 (2023-09-07) 阅读数 245 #CSS
文章标签 CSS3代码小记

CSS2

如果需要放大CSS2中的图像,则需要使用图像编辑器进行编辑以更改图像本身。

如果使用img标签,可以通过宽度和高度调整其大小,但如果需要将图像用作其他内容的背景,则此方法不起作用。

CSS3

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

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

Mozilla Firefox 4.0+ (Gecko 2.0+)、Microsoft Internet Explorer 9.0+、Opera 10.0+、Safari 4.1+ (Webkit 532) 和 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;
}

封面是当前项目中经常使用的属性,contain很容易与封面属性混淆。

与contain比较封面

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

contain和封面都会保持长宽比。

可以看到contain胸部高宽比例与图片不符时制造了一个缺口。

如果盒子的高宽比例与图像不一致,封面会导致剪裁。


额外注意点

如果所需的尺寸是静态像素尺寸,那么物理上实际图像尺寸仍然是正确的选择

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

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门