Search code examples
cssreactjsdropdownstyled-components

Drop down div not appearing on button hover, also z-index having no effect


I am building something in React with Styled-Components.

I am trying to have a div explaining the rules drop down when a button is hovered.

Everything is in good position, but the display: none is not disappearing when hovered.

I have had this kind of trouble every time I try to do such things, I have even copied code from previous attempts. I haven't been able to find any good rules on the web. If someone could link to a blog post or site that explains why it is the way it is, or explain to to me, that would be much appreciated.

JSX

<div className="rules-wrapper">
    <button id="rules-btn">
        <span role="img" aria-label="new game" className="hidden-icon">
            ❓
        </span>
        rules
    </button>
    <div className="rules-div">
        <h2>RULES:</h2>
        <p>Rule 1</p>
        <p>Rule 2</p>
        <p>Rule 1</p>
        <p>Rule 1</p>
        <p>Rule 1</p>
    </div>
</div>

STYLED-COMPONENTS

button {
    border: none;
    background: none;
    position: absolute;
    width: 200px;
    left: 50%;
    left: 50%;
    transform: translateX(-50%);
    color: #555;
    font-family: Lato;
    font-size: 20px;
    text-transform: uppercase;
    cursor: pointer;
    font-weight: 300;
    transition: background-color 0.3s, color 0.3s;
}

.rules-wrapper {
    left: 50%;
    transform: translateX(-50%);
    position: absolute;
    display: inline-block;
}

#rules-btn {
    top: 2rem;
}

#rules-btn:hover .rules-div {
    display: flex;
}

.rules-div {
    transform: translateX(-50%);
    display: none;
    position: absolute;
    left: 50%;
    top: 3.5rem;
    width: 20rem;
    transform: translateX(-50%);
    background: white;
    flex-direction: column;
    z-index: 5;
    border: 2px solid gray;
    padding: 2rem;
    align-items: center;
    box-shadow: 5px 5px 5px gray;
}

button:hover {
    font-weight: 600;
}

button:hover span {
    margin-right: 20px;
}

button:focus {
    outline: none;
}

span {
    display: inline-block;
    margin-right: 15px;
    line-height: 1;
    vertical-align: text-top;
    transition: margin 0.3s;
}

Solution

  • Looks like you already tried this:

    #rules-btn:hover .rules-div {
        display: flex;
    }
    

    This will not work because .rules-div is not a child of #rules-btn. But it is right next to each other (siblings), therefore you can use Adjacent sibling combinator

    #rules-btn:hover + .rules-div {
        display: flex;
    }