Grow your CSS skills. Land your dream job.

a:hover not applying to margin-top!

  • # August 25, 2012 at 7:28 pm

    I’ve been practicing web development for a few months, and I’m working on my website right now. I’ve run into a problem with “a:hover” not appying a change to the top margin. I’m wanting my navigation buttons to move up a few pixels up when the cursor moves over them for a cool effect, but I’ve tried it in Chrome, FF, and IE and it’s not working. Can someone please help?

    Both code examples are contained in a “header” div that is much larger than the button itself, if it helps to know that.

    Here’s the code for one button without a containing div (just an anchor tag with an id attribute).

    HTML:

    Home

    CSS:

    #indexImage {
    display:block;
    width:102px;
    height:29px;
    margin-top:75px;
    margin-left:77px;
    background-image:url(../Images/home-nav.png);
    background-repeat:no-repeat;
    overflow:hidden;
    white-space:nowrap;
    text-indent:100%;
    }

    #indexImage a:hover {
    margin-top:57px;
    }

    And here’s an example with a button in it’s own container the same size as the background image.

    HTML:

    CSS:

    #aboutNav {
    width:102px;
    height:29px;
    margin-top:75px;
    margin-left:77px;
    }


    #aboutNav a:hover {
    margin-top:57px;
    }

    #aboutImage {
    display:block;
    width:102px;
    height:29px;
    background-image:url(../Images/home-nav.png);
    background-repeat:no-repeat;
    overflow:hidden;
    white-space:nowrap;
    text-indent:100%;
    }
    # August 25, 2012 at 9:22 pm

    I believe this is due to margin collapsing. Specifically:

    “Margin collapsing happens wherever two (or more) top or bottom margins are touching. The basic idea is that when they touch, instead of getting the sum of the two margins, the bigger one is used, and the other is ignored.”

    If you remove the margin-top in #aboutNav, it works. However, it’s really jumpy, since you’re using a margin and it pushes the links layout below the user’s mouse (no longer hovering). I think to pull off what you want, just switch:

    #aboutNav a:hover {
    margin-top:57px;
    }

    to:

    #aboutNav a:hover {
    padding-top:57px;
    }

    Then you won’t have any collapsing, and the padding will keep the link’s layout where the mouse is when padding occurs on hover, so no jumping.
    Hope that helps.

    # August 25, 2012 at 10:52 pm

    its the selector – #indexImage a:hover {} is selecting an anchor within #indexImage. What you want is:
    a#indexImage:hover {}

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".