user2833068
user2833068

Reputation: 139

How do properly use CSS Image sprites?

I have a website i am trying to speed up and I am doing small things here and there. One of the things I would like to do but have not ever learned how to do is utilize image sprites.

Example here: http://flag-sprites.com/

Going to use the following code as an example:

<ul>
<li><div class"flag flag-zw"></div> Country Name</li>
<li><div class"flag flag-zw"></div> Country Name</li>
<li><div class"flag flag-zw"></div> Country Name</li>
<li><div class"flag flag-zw"></div> Country Name</li>
</ul>

I am trying to get the flags to show up beside the country name. This sprite comes pre positioned so that all I have to do is place the image and call the class. Any help would be greatly appreciated, thanks!

Upvotes: 1

Views: 3211

Answers (3)

Milan and Friends
Milan and Friends

Reputation: 5610

Here's a FIDDLE

<ul>
  <li><span class="flag flag-ad"></span>Country Name</li>
  <li><span class="flag flag-ae"></span>Country Name</li>
  <li><span class="flag flag-af"></span>Country Name</li>
  <li><span class="flag flag-ag"></span>Country Name</li>
</ul>


.flag {
  background: url(http://s22.postimg.org/u0nt2h8qp/flags.png) no-repeat;
  display: inline-block;
  margin-right: 10px;
  width: 16px;
  height: 11px;
}
.flag.flag-ad { background-position: -16px 0 }
.flag.flag-ae { background-position: -32px 0 }
.flag.flag-af { background-position: -48px 0 }
.flag.flag-ag { background-position: -64px 0 }

Fiddle result

Upvotes: 3

Riskbreaker
Riskbreaker

Reputation: 4791

Here you go:

I would make the flags span but div is fine too:

<li><span class="flag flag-aw"></span> Aruba</li>

CSS

.flag {width: 16px; height: 11px; background: url("http://static.flag-sprites.com/i/flags.png") no-repeat 0 0; margin-right: .3em; display: inline-block;}

.flag-aw {background-position: -224px 0;}

Example:

FIDDLE

..Theres no need to bother with "blank.gif" . If you have Phtoshop or GIMP(free) you can get the proper dimensions where the images are positioned.

Upvotes: 0

Scott S
Scott S

Reputation: 389

It looks like the code examples already posted will get you what you need. But, in addition to that I would like to suggest the tool Sprite Cow. This tool makes finding css position values very easy.

Upvotes: 1

Related Questions