-1

This code above is a simple example, I want to use opacity and absolute to build a drop down menu. When the mouse hover on the parent container, then the child content shows. But it doesn't work at all.

.child {
    background-color:blue;
    height:200px;
    position:absolute;
    top:50px;
    opacity:0;
}
 
.parent {
    position:relative
}
.parent:hover + .child {
    opacity:1
}  
<html>
    <body>
        <div class="parent">
            <div class="child"></div>
        </div>
    </body>
</html>
WOWOW
  • 91
  • 8
John Paul
  • 9
  • 1
  • There's nothing special about setting the opacity for absolutely positioned elements, your example simply has other issues. Firstly, you haven't set a height on the parent (or given it any content), so it has a height of 0 and can't be hovered. Secondly, you haven't set a width on the child, so it has a width of 0 and isn't visible. Finally, `+` is used to select _adjacent_ elements, not _child_ elements --- you probably want to use `>` instead. – Toastrackenigma Aug 26 '23 at 18:23
  • Yes, that code is just a simple example, sir now it works~ thanks! – John Paul Aug 26 '23 at 18:28

1 Answers1

0

.child {
    background-color: blue;
    height: 200px;
    position: absolute;
    top: 50px;
    opacity: 0;
    transition: opacity 0.3s; /* Add a transition for smooth effect */
}

.parent:hover .child {
    opacity: 1;
}

.parent {
    position: relative;
    width: 200px; /* Adding width for demonstration */
    height: 100px; /* Adding height for demonstration */
    background-color: lightgray; /* Adding background for demonstration */
}
<!DOCTYPE html>
<html>
    <body>
        <div class="parent">
            Hover me
            <div class="child">
              Dropdown content
            </div>
        </div>
    </body>
</html>

The + which you have used in the CSS is wrong.

WOWOW
  • 91
  • 8
Balaji Venkatraman
  • 1,228
  • 12
  • 19