user153923
user153923

Reputation:

Display Image in Horizontal UL LI with Sprite in CSS

Image Sprites, by themselves, are not evil; however, trying to get these to work in an unordered list is difficult. Going a step further and trying to get this unordered list to display horizontally (working example >> HERE <<) is certainly an enigma.

Here is my jsFiddle Project: jsFiddle: hNJmD

It seems like every time I get something working, I make the smallest edit to customize it for my app and it breaks.

Here is the image I am using as my Sprite:

Sprite

My Goal:

The CSS is:

#nav {
  text-shadow: 4px 4px 8px #696969;
  white-space:nowrap;
  vertical-align: middle;
}
#nav ul {
  list-style-type:none; /* removes the bullet from the list */
}
#nav li {
  display: inline-block;
  text-align: center;
  height: 50px;
  width: 192px;    
}
#nav a {
  background: url('http://i.imgur.com/Sp7jc.gif') 0 -100px no-repeat;
  display: block;
  color:Blue;
}
#nav a:hover {
  background-position: 0 -50px;
  color:Red;
}
#nav .active, a:hover {
  background-position: 0 0;        
  color:Black;
}
#nav span {
  top: 15px;
  padding-left: 5px;
}
​

The HTML used in the jsFiddle is repeated here as well:

<body>
  <div>
    <ul id="nav">
      <li>
        <a class="active" href="#">
          <span>Link 1</span>
        </a>
      </li>
      <li>
        <a href="#">
          <span>Link 2</span>
        </a>
      </li>
      <li>
        <a href="#">
          <span>Link 3</span>
        </a>
      </li>
    </ul>
  </div>
<br/>
<br/>
<br/>
<br/>
<div style="text-align:center;">
  <p>REFERENCE: Sprite (Width: 192, Height: 150):</p>
  <img src="http://i.imgur.com/Sp7jc.gif">
</div>
</body>​

Can somebody show me how to get this crazy thing to work?

Upvotes: 0

Views: 4059

Answers (1)

j08691
j08691

Reputation: 207901

If you want it to look like this: jsFiddle example, then this is what I did:

  • Combined your #nav and #nav ul rules since they refer to the same thing.
  • To that rule I added margin:0 auto; and width:600px; which centers the items
  • Then on #nav a I added display: block; and height:50px; which allows the links to take up the proper amount of height.
  • Finally I added a rule, #nav .active:hover that only affects the active element so it doesn't appear to change.

And to answer one of your questions about whether the order of CSS rules matters, the answer is yes and no. With respect to width and height in a rule, the order is irrelevant, but the order the rules appear in can matter, as does the specificity of the rule.

Upvotes: 1

Related Questions