使背景图片适合具有动态宽度的 div 元素

Fit background image on div element with dynamic width

如果我们为该图像指定了背景位置,如何使 div 适合其容器的 100% 并保持相同的背景图像?

CSS

#content {
    position: relative;
    max-width: 50%;
    height: 0;
    padding: 0 0 50% 0;
}
.icon-1 {
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%; 
   background: url( "/path/to/my/image.png" ) no-repeat -50px -50px;
  /*
  -50px -50px is corresponding to letter "D" in the image
  */
 }

HTML

<div id='content'>
   <div class='icon-1'>
   </div>
</div>

想法是使用一个文件来制作一些类似图标的图像(以直观地表示每个购物类别)

#content {
    position: relative;
    max-width: 50%;
    height: 0;
    margin: 0 auto 0 auto;
    padding: 0 0 50% 0;
}
.icon-1 {
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%; 
   background: url( "https://i.stack.imgur.com/4FzW2.png" ) no-repeat -50px -50px #aa0000;
  /*
  -50px -50px is corresponding to letter "D" in the image
  */
 }
<div id='content'>
   <div class='icon-1'>
   </div>
</div>

您只需要调整背景值即可。在您的情况下,它应该是红色框大小的 2 倍,然后将位置调整为 bottom/right 以使 D 和 top/left 对应 A 等等:

#content {
  position: relative;
  max-width: 50%;
  height: 0;
  margin: 0 auto 0 auto;
  padding: 0 0 50% 0;
}

.icon-1 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url("https://i.stack.imgur.com/4FzW2.png") bottom right/200% 200% no-repeat;
}
<div id='content'>
  <div class='icon-1'>
  </div>
</div>