CSS设置背景图片

一、图片不变形(推荐使用img标签)

1. 宽高都不固定

<!-- 只需要设置src即可 -->
<img src="test.png">

2. 宽高比固定

图片宽高比和标签宽高比相等则使用img和背景图方式都是一样的

img标签方式

<img src="test.png">

背景图片方式

.img {
  background-image: url(\'test.png\');
  background-repeat: no-repeat;  
  background-size: 100% 100%;      
}

3. 宽或高有一个固定

使用img和使用背景图方式各有利弊

使用img会出现变形

使用背景图又分为好多种情况

// 这种方式和使用img没有区别
.img {
  background: url(\'test.png\') no-repeat; 
  background-size: 100% 100%;      
}

// 这种方式背景图片不变形,但只会展示图片的一部分,展示的内容是根据background-position和宽高决定的,top center决定了从顶部和中心位置不变始终在展示
// background-position的属性可以查看 
 https://www.runoob.com/cssref/pr-background-position.html
.img {
  background: url(\'test.png\') no-repeat top center;
  background-size: cover;
}