0

I have two div's inside of a containing div.

The first of the two will have a word used as a menu item and the second will hold a background color.

I created a hover style for the background that will change the opacity of that div when the menu item is moused over.

My problem is that hover is only enabled when the mouse is right on the edges of the div. As soon as my mouse moves a little into the interior of the div, it reverts back to the original opacity.

My style:

.menuItemBG {
    width:100%;
    text-align: center;
    background-color:#4281b6;
    height:100%;

    /* These three lines are for transparency in all browsers. */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=10)";
    filter: alpha(opacity=10);
    opacity:.1;
    position: absolute;
}
.menuItemBG:hover {
    width:100%;
    text-align: center;
    background-color:#4281b6;
    height:100%;

    /* These three lines are for transparency in all browsers. */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";
    filter: alpha(opacity=20);
    opacity:.2;
    position: absolute;
}
.menuItemTitle{
    position:relative;
    color:#000;
    line-height: 27px;
    font-size: 14px;
    margin-left: 20px;
}

HTLML:

<div style="position:relative; width:208px; height:30px;">
    <div class="menuItemBG"></div>
    <div class="menuItemTitle">Test Item</div>
 </div>

Can't seem to pinpoint my error.

1 Answer 1

2

When you hover over the menuItemTitle, you are no longer hovering over menuItemBG because they are siblings in the DOM. You can switch the :hover to the div that contains them, and apply the styles to menuItemBG that way. If you give the containing div the class menuItem, you can do:

.menuItem:hover .menuItemBG {
    /* These three lines are for transparency in all browsers. */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";
    filter: alpha(opacity=20);
    opacity:.2;
}

Notice I did not repeat the CSS that applies regularly to .menuItemBG. It is not needed. So then add the class menuItem to your containing div:

<div class="menuItem">
    <div class="menuItemBG"></div>
    <div class="menuItemTitle">Test Item</div>
</div>

You can move that inline CSS you had for .menuItem to your stylesheet quite easily now. It works either way, but moving it to the stylesheet is cleaner and easier to maintain.

.menuItem {
    position: relative;
    width: 208px;
    height: 30px;
}

Demo: http://jsfiddle.net/fYQfX/1

Sign up to request clarification or add additional context in comments.

1 Comment

I made some edits that apply to stylistic suggestions. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.