What is the best way to do an inline image sprite?

2019-06-08 03:10发布

After some reasearch I found that I can stretch a transparent GIF to the sprite size and set the background to the sprite image with offset.

See: http://jsfiddle.net/iambriansreed/6bT3j/embedded/result

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP//////zCH5BAEHAAAALAAAAAABAAEAAAICRAEAOw=="
    width="30" height="30" style=" background: -88px -223px 
        url('http://ssl.gstatic.com/gb/images/j_f11bbae9.png');"
>

Is this the best, cleanest way to go about creating an inline image sprite?

标签: html sprite
2条回答
beautiful°
2楼-- · 2019-06-08 03:26

I believe my way as described above is the best way to load an image sprite.

I added only the CSS needed to view that sprite and left all other CSS in the StyleSheet where it belongs.

While the true source of the image is a transparent GIF whether you use an actual gif or the data equivalent in my example above the sprite image is set as the background and offset to reveal the needed sprite.

It makes it possible to use the img tag for it's intended purpose: such as the alt attribute, and the tag's default inline display.

A single image tag with certain inline css is a lot less html than anything else I have seen and semantic html can be added where needed.

查看更多
Fickle 薄情
3楼-- · 2019-06-08 03:35

Below is Google's homepage CSS Sprite (you'll see no transparent gif is required).

If the image has semantic meaning, for example it's a logo or a picture central to an article then this is the best technique to use.

But if the image you're loading has no semantic meaning e.g. it's a navigation image which is there for decoration only, then you might want to use CSS to load the image rather than an image tag.

Google CSS Sprite

enter image description here

HTML

<div class="nojsv" id="logocont" style="left: 0px; position: absolute; visibility: visible; ">
  <h1>
    <a id="logo" href="https://www.google.co.uk/webhp?hl=en" title="Go to Google Home">
      Google
        <img width="167" height="389" src="/images/nav_logo104.png" alt="">
    </a>
  </h1>
</div>

CSS

#logo {
  display: block;
  height: 41px;
  margin: 0;
  overflow: hidden;
  position: relative;
  width: 114px;
}
查看更多
登录 后发表回答