Search code examples
htmlcsspositioningbackground-image

How do I stop the text from moving when hovered? (background-image is involved)


This is basically the problem that I am facing now, http://jsfiddle.net/NCJeP/.

HTML

      <nav>
    <ul id="city-navigation">
        <li><a href="../chennai/" class="active">Chennai</a></li>
        <li><a href="../trichy/">Trichy</a></li>
        <li><a href="../madurai/">Madurai</a></li>
        <li><a href="../coimbatore/">Coimbatore</a></li>
        <li><a href="../salem/">Salem</a></li>
    </ul>
    </nav>​

CSS

#city-navigation {
    width: 100%;
    position: relative;
    left: 10px;
}

#city-navigation li a {
    float: left;
    font: 14px Rockwell, Georgia, Times, “Times New Roman”, serif;
    margin: 20px 20px;
    color: #FFF;
}

#city-navigation li a:hover {
    background-image: url(http://i.imgur.com/QVzKG.png);
    background-repeat: no-repeat;
    color: #000;
    width: 116px;
    height: 60px;
    display: block;
    text-align: center;
    position: relative;
    z-index: 4;
}

#city-navigation .active {
    background-image: url(http://i.imgur.com/HbLa1.png);
    background-repeat: no-repeat;
    color: #000;
    width: 116px;
    height: 60px;
    display: block;
    text-align: center;
}​

I can't seem to figure out how I can stop the text from moving to the right because of the extra width that the background image adds. I know there is enough space, I just want the image & text to be static.

If anyone can help out, I'd be very much thankful! =) Cheers!


Solution

  • The width on your hover is causing the jump. I moved it to the "a" tag and cleaned up the other code a bit as well:

    #city-navigation li a {
        float: left;
        font: 14px Rockwell, Georgia, Times, “Times New Roman”, serif;
        margin: 20px 20px;
        color: #FFF;
        display: block;
        text-align: center;
        width: 116px;
        height: 60px;
    }
    #city-navigation li a:hover {
        background: url(http://i.imgur.com/QVzKG.png) no-repeat;
        color: #000;
    }
    #city-navigation .active {
        background: url(http://i.imgur.com/HbLa1.png) no-repeat;
        color: #000;
    }