从css图像精灵中检索图像与不同大小的图像

时间:2018-03-29 21:49:21

标签: php html css

我的目标是做一个国际象棋游戏或实际上只是为了它的乐趣:-)有几个棋子的简单方法是每个国际象棋有一个图像,但这将是很多http-请求似乎没必要。

我想使用https://commons.wikimedia.org/wiki/File:Chess_Pieces_Sprite.svg

中的图片

并检索具有背景位置的图像,这不会有问题......

但问题是棋盘和它的正方形并不总是相同的大小(它必须是响应的)我希望每个精灵充当普通图像并相应地调整大小。

我已尝试使用background-sizebackground-size以及包装组合,但显然我错过了一些东西。也许在这种情况下这是错误的做法?你觉得怎么样?

我也考虑过“切片”精灵图像并从php创建图像,但我认为使用css将是一个更好的解决方案。

如果我喜欢这个html(由html生成) - 我想查看chesspieces.png(尺寸为2000x667)的缩放版本,因此它适合此div并相应缩放但仅显示chesspieces.png文件的一部分,例如车。我希望你明白我的意思!?

<div style="float:left;background:#ffffff;
width:100px;height:100px;" 
class="square"><img src="chesspieces.png">
</div>

请告知您是否需要更多信息!

更新 感谢您的投入!

我试过这个:

<div style="width:100px;height:100px;background: #ffffff 
url('chesspieces2000.png') -20% 40% no-repeat;background-size: cover; 
class="square"></div>

enter image description here 我把它放在y pos%中它不起作用。我希望图像填满整个方块,因此我使用background-size:cover

我也试过背景位置y:40%但没有任何反应。我可以用固定的像素值改变ypos。这应该以这种方式运作吗?

澄清:

我有这个输出: enter image description here

并使用此html:

<div class="square" 
style="float:left;width:100px;height:100px;background:#000000"><div 
style="width:100px;height:100px;background:#000000 
url('chesspieces2000.png') 0 0 no-repeat;background-size:100%;" 
class="square"></div></div>

我想取一个国际象棋比例,所以它覆盖了100%宽度和高度自动的方块。

UPDATE2:

感谢@Robo Robok谢谢! - 我解决了这个问题,但是一些与价值观相结合使得它按照我的意愿运作了!

<div style="width:100%;height:100%;
background:#ffffff url('chesspieces2000.png') 19% -10% no-repeat;
background-size:auto 170%;"></div>

这是女王! :-) enter image description here

当调整图像包装器的大小时:

这也很好用。它涵盖了所有广场!

<div style="width:100%;height:100%;
background:#ffffff url('chesspieces2000.png') 20% 0% no-repeat;
background-size:auto 200%;"></div>

enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个:

<div style="width: 100px;
            height: 100px;
            background: url('chess.svg') no-repeat 40% 100%;
            background-size: auto 200%;"></div>

background-size需要为auto 200%,因为您的精灵中有2行,这意味着整个背景需要占据元素高度的两倍。

每个精灵的背景位置是:

  • 第一行:0 020% 040% 0,... 100% 0
  • 第二行:0 100%20% 100%40% 100%,... 100% 100%