Search code examples
htmlcssalignmentdropdownpositioning

Positioning in CSS,I need the drop down options central but indented left


Below HTML requires suitable CSS for the drop down links to be central but indented. view fiddle. https://jsfiddle.net/peteraejnrdev/865h2tvu/2/#&togetherjs=d3VifH4hc3

<div class="header-dropdown-menu">
      <ul class="top-nav">
          <li class="top-menu-nav"><a href="#">Menu</a>
            <ul class="sub-nav">
              <li><a href="#">wood Type</a></li>
              <li><a href="#">News</a></li>
              <li><a href="#">Specification</a></li>
              <li><a href="#">Pricing</a></li>
              <li><a href="#">Images</a></li>
              <li><a href="#">FAQ</a></li>
            </ul>
          </li>
        </ul>
      </div> 

Solution

  • This could be done using the position property -

    Set the parent to position relative (this creates the container for the child elements) the set the child element position to absolute. You can now dictate using the top/left/bottom/right properties where you want to place the element - Keep in mind that the center point of the elements will by default be placed in the top left - this means you will need to transform the elements by -50% (top and left) to center them - Example below:

    li.top-menu-nav {
        position: relative;
        width: 100%;
    }
    
    ul.sub-nav {
        position: absolute;
        left: 50%;
        transform: translate(-50%);
    }
    

    Please keep in mind if you would like to center the LI's you would need to add -

    ul.sub-nav {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, 50%);
    }
    

    also, note that the height that the child (li in this case) can be moved to will depend on the height of the parent element, giving your top-menu-nav a height:100vh will allow the menu to be placed in the center of the page.

    Hope this helps, Wally