在HTML 5中显示图像的一部分

时间:2013-10-27 12:31:40

标签: html css html5 css3 css-sprites

考虑我的图像包含100个图标,大小为16x16。因此图像大小为1600x16。 现在我想要一个HTML 5标记来显示nth图片。 什么是HTML语法来定义要显示的图像的特定部分

<img src="pic.jpg" height="16" width="16" offsetOrSomething=??/>

2 个答案:

答案 0 :(得分:5)

将图片用作背景并使用background-position移动它..

<span class="icon nth"></span>

.icon{
  width:16px;
  height:16px;
  display:inline-block;
  background-image: url('pic.jpg');
}
.icon.nth{
  background-position:-32px -16px; /*both left and top should be multiples of the icon dimensions*/
}

如果您 就像在您的示例中那样做,那么您需要再次使用overflow:hidden的包装,然后将图像移到其中。

<span class="icon-wrapper"><img src="pic.jpg" style="left:-16px;top:-32px;" /></span>

.icon-wrapper{
    width:16px;
    height:16px;
    display:inline-block;
    overflow:hidden;
    position:relative;
}
.icon-wrapper img{position:absolute;}

答案 1 :(得分:-1)

一种简单的方法是约束父级的尺寸以裁剪图像......

<div style="height:10px; overflow-y:hidden;">

    <img src="pic.jpg" height="16" width="16" />

</div>

尝试将边距顶部设置为负值以查看隐藏部分。