Search code examples
htmlcssdrop-down-menudropdowncascadingdropdown

Fix clustered list in dropdown HTML/CSS


I'm trying to make a dropdown menu, and what I try to make one, the list items in the menu get all clustered up in the same line. I just can't seem to figure out the problem. I've trying changing display properties, editing margins & paddings, but for some reason it just doesn't seem to work. I would really appreciate if anyone were able to help.

HTML

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv=”Cache-Control” content=”no-cache, no-store, must-revalidate”>
    <meta http-equiv=”Pragma” content=”no-cache”>
    <meta http-equiv=”Expires” content=”0”>
    <link rel="stylesheet" type="text/css" href="css/nav-style.css">
</head>

<body>
    <nav>
        <ul>
            <li>Home</li>
            <li class="dropdown-button">Forums


                <ul class="dropdown">
                    <li>Staff</li>
                    <li>Complaints</li>
                    <li>Applications</li>
                </ul>

            </li>
            <li>Store</li>
        </ul>

    </nav>
    <script>
        for(var i = 0;i<100;i++) {
            document.writeln("<br>");
        }

    </script>
</body>

CSS

nav {
    /* height: 70px; */
    background-color: rgb(66, 66, 66);
    z-index: 3;
    width: 100%;
    min-width: 236px;
}

nav > ul {
    display: inline-block;

    width: 100%;
    min-width: 240px;
    padding-left: 0;
}

nav > ul > li {
    display: inline-block;
    font-size: 2.2em;
    text-align: center;
    width: 33%;
    min-width: 150px;
    text-transform: uppercase;
}
nav > ul > li:hover {
    cursor: pointer;
}

nav > ul > li:after {
    top: 15px;
    content: '';
    display: block;
    border-bottom: 3px solid red;
    width: 100%;
    transform-origin: 50%;
    transform: scaleX(0);
    transition: transform 0.7s ease-in-out;
}

nav > ul > li:hover:after {
    transform: scaleX(1);
}

.dropdown li {
    position: absolute;
    font-size: 0.7em;
    display: block;
    width: 100%;
    text-transform: none;
    margin-right: 100%;
}

.dropdown {
    display: none;
    height: 100%;
}

.dropdown-button {
    height: 100%;
}

.dropdown-button:hover .dropdown {
    display: block;
}

My Code (Fiddle):
https://jsfiddle.net/6b4epg7a/

Thanks in advance!


Solution

  • You need to add position: relative to the dropdown's parent li:

    .dropdown-button {
        position: relative;
    }
    

    and position:absolute to to the child element.

    .dropdown {
        position: absolute;
        display: none
    }
    
    .dropdown li {
      line-height: 27px;
      font-size: 0.7em;
      text-transform: none;
      list-style: none;
    }
    

    check jsfiddle: https://jsfiddle.net/nza9gy8k/1/

    To learn more about positioning in css. check https://developer.mozilla.org/en-US/docs/Web/CSS/position