【问题标题】:Fit background image on div element with dynamic width在具有动态宽度的 div 元素上调整背景图像
【发布时间】:2018-04-25 23:05:09
【问题描述】:

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

【问题讨论】:

  • 你的意思是你想让 D 适合所有的红色块?
  • 是的,这就是我想要的。这可能吗?

标签: html css background-image


【解决方案1】:

您只需要调整背景的值。在您的情况下,它应该是红色框大小的 2 倍,然后将位置调整为底部/右侧以具有 D 和顶部/左侧为 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>

【讨论】:

  • 这就是我想要的。我将把大约 20 张图像放在一个文件中,并以百分比进行播放。谢谢
猜你喜欢
  • 2012-04-10
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 2021-12-21
  • 1970-01-01
相关资源
最近更新 更多