首页 > 解决方案 > 将背景图像拟合到 div

问题描述

我正在使用以下 css 使 div 在屏幕上始终全尺寸,

.container{
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  overflow: auto;
  background: url("../assets/shutterstock_585038551.jpg");
  /*border: 1px solid black;*/
} 

但是只有一部分背景图像显示出来,如何在不改变其纵横比的情况下适应背景图像。

标签: css

解决方案


将以下内容添加到您的 CSS。

background-size: cover;
background-repeat:no-repeat;

这假设您的.containerdiv 是全宽和全高。

如果不是,还添加以下内容:

width: 100vw;
height:100vh;

关于背景大小的一些信息。

https://www.w3schools.com/cssref/css3_pr_background-size.asp

https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

vh关于和的一些信息vw

https://css-tricks.com/fun-viewport-units/


推荐阅读