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

meh*_*dvd 3 html css html5 css-sprites css3

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

<img src="pic.jpg" height="16" width="16" offsetOrSomething=??/>
Run Code Online (Sandbox Code Playgroud)

Gab*_*oli 5

使用图像作为背景并使用background-position移动它..

<span class="icon nth"></span>
Run Code Online (Sandbox Code Playgroud)

.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*/
}
Run Code Online (Sandbox Code Playgroud)

如果你必须像在你的例子中那样做,那么你需要再次使用一个包装器overflow:hidden,然后在其中移动图像.

<span class="icon-wrapper"><img src="pic.jpg" style="left:-16px;top:-32px;" /></span>
Run Code Online (Sandbox Code Playgroud)

.icon-wrapper{
    width:16px;
    height:16px;
    display:inline-block;
    overflow:hidden;
    position:relative;
}
.icon-wrapper img{position:absolute;}
Run Code Online (Sandbox Code Playgroud)