首页 > 解决方案 > 背景图像没有响应的问题

问题描述

我正在尝试使背景图像响应媒体查询,但图像保留其原始大小。

我看不出我在哪里做错了。我很感激任何帮助

#wrapper{
   background: url(https://via.placeholder.com/1500x1000) center center cover no-repeat fixed;
   display: flex;
   justify-content: center;
   align-items: center;
   width: 100vw;
   height: 100vh;
}

@media (min-width:1201) {
  #wrapper {
    background-image: url(https://via.placeholder.com/1300x900);
  }
}

@media (max-width:1200px) and (min-width:901) {
  #wrapper{
    background-image: url(https://via.placeholder.com/900x750);
  }
}

@media (max-width:900px) and (min-width:601) {
  #wrapper {
    background-image: url(https://via.placeholder.com/800x650);
  }
}

/* For mobile devices */
@media only screen and (max-width: 600px) {
  #wrapper{
    
    background-image: url(https://via.placeholder.com/500x405);
  }
}
<div id="wrapper">

</div

标签: cssresponsive

解决方案


检查 HTML 会发现您的background属性无效。尝试

#wrapper{
   /* mobile first this image and move to wherever you intended this one */
   background: url(https://via.placeholder.com/1500x1000) center center no-repeat;
   background-size: cover;
   background-attachment: fixed;
   display: flex;
   justify-content: center;
   align-items: center;
   width: 100vw;
   height: 100vh;
}

您的其余查询可以使用一些清理

/* For mobile devices */
@media only screen and (max-width: 600px) {
  #wrapper{
    background-image: url(https://via.placeholder.com/500x405);
  }
}

@media (min-width:601px) {
  #wrapper {
    background-image: url(https://via.placeholder.com/800x650);
  }
}

@media (min-width:901px) {
  #wrapper{
    background-image: url(https://via.placeholder.com/900x750);
  }
}

@media (min-width:1201px) {
  #wrapper {
    background-image: url(https://via.placeholder.com/1300x900);
  }
}

推荐阅读