在动态宽度为

时间:2018-04-25 23:05:10

标签: html css background-image

如果我们为该图像指定了背景位置,如何将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>

test image

1 个答案:

答案 0 :(得分:1)

您只需调整背景值即可。在您的情况下,它应该是红色框大小的2倍,然后将位置调整为底部/右侧,以DA的顶部/左侧,依此类推:

&#13;
&#13;
#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;
}
&#13;
<div id='content'>
  <div class='icon-1'>
  </div>
</div>
&#13;
&#13;
&#13;