html添加背景图片并且填满div,css background-size与背景图片填满div(示例代码)

background-size与背景图片填满div

在开发中,常有需要将一张图片作为一个div的背景图片充满div的需求

background-size的取值及解释

background-size共有三种属性,分别为

background-size: cover

MDN文档解释说明:缩放背景图片以完全覆盖背景区,可能背景图片部分看不见。A keyword that is the inverse of contain. Scales the image as large as possible and maintains image aspect ratio (image doesn‘t get squished). The image "covers" the entire width or height of the container. When the image and container have different dimensions, the image is clipped either left/right or top/bottom.

这里的关键说明在于标红的两个区域,分别是它会保持图片的宽高比和当图像和容器具有不同的尺寸时,图像被左/右或顶部/底部裁剪。之后会结合例子说明

background-size: contain

MDN文档解释说明:缩放背景图片以完全装入背景区,可能背景区部分空白。A keyword that scales the image as large as possible and maintains image aspect ratio (image doesn‘t get squished). Image is letterboxed within the container. www.97yingyuan.org When the image and container have

你可能感兴趣的:(html添加背景图片并且填满div,css background-size与背景图片填满div(示例代码))