-1

I have a menu (left navigation) which has sub menus that fly out when hovered over. It is comprised of unordered lists stacked like so:

<ul>
   <li>Item</li>
   <li>Item w/ Sub
       <ul class="sub">
            <li>sub 1</li>
       </ul>
   </li>
<ul>

This is really its most simple form. Right now the hovering works fine, what I would like to do is to make the vertical centers of the parent menu and the fly-out submenu line up. This image demonstrates the idea:

Current State

Current Functionality

Desired State

Desired Functionality

As you see in the image, the vertical centers (the line spanning halfway up the height of the elements), is basically in line with each.

Right now, the green child is absolutely positioned, but when I add relative positioning to the parent child, it starts to exhibit some erratic and bizarre behavior. I was wondering if there was a way to do this with flexbox, but I have yet to find a solution.

How can I get the vertical centers of a parent and child to align?

Things to consider:

  • The submenus are variable height
  • They are fixed width (260px)
  • The parent menu (blue box) is a fixed height.
Barry Chapman
  • 6,690
  • 3
  • 36
  • 64

1 Answers1

1

This code should work :

.sub {
  position: absolute;
  top: 50%;
  left: 100%;
  transform: translateY(-50%);
  ...
}

Exemple :

.menu {
  display: inline-block;
  list-type: none;
  padding-left: 0;
  border: 1px solid black;
}

/* First-level children */
.menu > li {
  position: relative;
  background: #eee;
  padding: 16px;
}

.menu > .parent {
  background: yellow;
}

.menu > .parent:hover {
  background: gold;
}

.menu > li + li {
  border-top: 1px solid grey;
}

/* Second-level children */
.parent:hover .child {
  display: block;
}

.child {
  display: none;
  position: absolute;
  top: 50%;
  left: 100%;
  transform: translateY(-50%);
  list-style-type: none;
  padding-left: 0;
  border: 1px solid black;
}

.child > li {
  background: orange;
  padding: 8px;
  white-space: nowrap;
}

.child > li + li {
  border-top: 1px solid grey;
}
<ul class="menu">
 <li>Menu 1 (no hover)</li>
 <li class="parent">
   Menu 2 with child : hover this one
   <ul class="child">
     <li>Menu 1</li>
     <li>Menu 2</li>
     <li>Menu 3</li>
   </ul>
 </li>
 <li>Menu 3 (no hover)</li>
</ul>
Jeyffrey
  • 96
  • 1
  • 5