Alignment of sub-menu

I have created a menu with dropdown sub-menus. All is well except I can’t get the sub-menus to align horizontally with the parent menu item. The following pen shows the problem:

I’ve tried a %age left but the -3em seems like a bit magic numberish.

Hi there gandalf458,

try these amendments…

.container {
  /*max-width: 1200px;*/max-width: 75em;
  margin: 0 auto;
  padding: 2rem 0 0.5rem;
}


.headerWrap {
  /*max-width: 720px;*/max-width: 45em;
  width: 100%;
  margin: 0 auto;
}


nav ul ul {
  z-index: 1;
  position: absolute;
  top: auto;
  /*left: -3em;*/ left: 0;
  margin-top: -99em; 
}

nav ul ul li {
  width: 12em;
  /*text-align: center;*/ text-align: left;
  background-color: rgba(255, 255, 255, 0.9);
}



Have you considered the hover problem for small devices?

coothead

1 Like

Then try have the sub-list in center of the li parent so its (width-less) items can center in the sub-list. The sub-list and its inline-block items inherits the center alignment:

nav ul ul {
  z-index: 1;
  position: absolute;
  top: auto;
  left: -2em;
  right: -2em;
  margin-top: -99em;
}
nav ul ul li {
  width: auto;
  background-color: rgba(255, 255, 255, 0.9);
}

Maybe this could also be considered magic numberish, as the inline sub-items could sit on the same line if the ul width is wide enough. :slight_smile:

Edit)
Magic numberish; The risk of short items on the same line could be safer avoided by widening the anchors and the sub-list to make better room for longer anchor texts:

nav ul ul {
  z-index: 1;
  position: absolute;
  top: auto;
  left: -5em;
  right: -5em;
  margin-top: -99em;
}
nav ul ul li a {
  padding: 3px 2em;
}

Thinking again I reckon it’s better to use flex-box to distribute and center the links. (Sub-items and anchors are width-less.) This would work for link texts of any practical lengths:

nav ul ul {
  z-index: 1;
  position: absolute;
  top: auto;
  left: -12em;
  right: -12em;
  margin-top: -99em;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

There are more options to achieve this but I think this is to prefer. :slight_smile:

1 Like

That’s on the list! :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.