【问题标题】:How to use a sprite for a background on a div, positioning to a part of the sprite to the right of the div如何在 div 上使用精灵作为背景,定位到 div 右侧的精灵的一部分
【发布时间】:2014-06-19 05:50:09
【问题描述】:

我要应用背景的 div 比我的 sprite 大,我要用作背景的 sprite 部分距离 sprite 顶部 100px。

如何将 div 的背景设置为我想要的精灵的一部分,并且让它位于 div 的右侧。

我有什么:http://jsbin.com/yibesu/1/edit?html,css,output

我希望将“我想要的”背景推到 div 的右侧,其余部分为红色。

我的 CSS:

div { 
  background: url('http://i.imgur.com/VBe5ey2.png') red;
  background-position: 0 -100px;
  background-repeat: no-repeat;
  width: 400px; 
  height: 200px; 
}

就像我希望背景位置为“0 -100px”并且被推到 div 的右侧。精灵的宽度小于 div。这可能吗?或者我是否需要从精灵中撕下部分并让它成为自己的图像?谢谢!

【问题讨论】:

标签: css sprite


【解决方案1】:

你已经接近了。您唯一需要做的就是使用background-position 将其与右侧对齐。新的css如下:

div { 
  background: url('http://i.imgur.com/VBe5ey2.png') red;
  background-position: right -100px;
  background-repeat: no-repeat;
  width: 400px; 
  height: 200px; 
}

我用 Firefox、Chrome 和 IE11 对其进行了测试,似乎一切正常。

【讨论】:

    【解决方案2】:

    当我想这样做时,我会将我的精灵定位在精灵 PNG 的右侧,并在其下方留有足够的垂直空间以确保图形中的下一个精灵不会在 div 的底部可见。

    在 CSS 中,我将背景图像的水平位置定义为 right:

    div { 
      background: red url('sprite.png') right -100px no-repeat;
    }
    

    这是您的 JSBin 的编辑版本:http://jsbin.com/kohivibu/1/edit

    【讨论】:

      猜你喜欢
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多