以下是几种实现div
背景图片自适应的方法及代码示例:
一、使用 CSS 的background-size
属性
div { width: 300px; height: 200px; background-image: url('your-image.jpg'); background-size: cover;}
div { width: 300px; height: 200px; background-image: url('your-image.jpg'); background-size: contain;}
二、使用 CSS3 的background-size
百分比值
div { width: 300px; height: 200px; background-image: url('your-image.jpg'); background-size: 100% 100%;}
三、使用vw
和vh
单位
div { width: 300px; height: 200px; background-image: url('your-image.jpg'); background-size: 100vw 100vh;}
四、使用 CSS3 的object-fit
属性(适用于设置了background-image
为url()
且同时设置了background-size
为cover
或contain
后仍无法满足需求的情况)
div { width: 300px; height: 200px; background-image: url('your-image.jpg'); background-size: cover; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-repeat: no-repeat; position: relative;}div::before { content: ""; display: block; padding-top: 100%; /* 保持宽高比为 1:1 */}div::after { content: ""; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-image: inherit; background-size: cover; background-repeat: no-repeat; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; object-fit: cover;}