简体   繁体   中英

CSS hover dropdown menu, position absolute?

The best way to describe this issue is with pictures (Don't mind the Dutch), I'm stuck with this at the moment: Example1

In the first example you can see that the red dropdown hover lines with the parent in this case. What I want is this: Example2

The way I did it in Example2 was with element inspect and changing the Ul's manually with margin-top (40px). Which means I have to do 80px, 120px etc. On the next couple of menu links.

Is there an easier way?

Thanks in advance!

Position the dropdown menu relative to the menu container ( <ul> ) instead of the menu item ( <li> ).

A simple example on jsFiddle .

The relative HTML:

<ul class="outer">
  <li>
    Beelden

    <ul class="sub-menu">
      <li>Geurkaarsen</li>
      <li>Rituele kaarsen</li>
      <li>Affirmatie kaarsen</li>
    </ul>
  </li>
</ul>

And CSS:

/* Your outer menu */
ul.outer {
  position: relative;
}

li {
  /* Whatever styles you set here, don't give it relative positioning */
}

ul.sub-menu {
  position: absolute;
  top: 0;
  right: -100%;
  width: 100%;
}

Live demo:

 * { box-sizing: border-box; margin: 0; padding: 0; } body { height: 100vh; } body > ul { /* This next line is crucial */ position: relative; background-color: #c5e2d8; width: 30%; height: 100%; } ul.sub-menu { display: none; position: absolute; top: 0; right: -100%; width: 100%; background-color: tomato; } li { display: block; color: #444; padding: .5em; cursor: pointer; } li.has-children::after { content: '▸'; position: absolute; right: 5px; } li:hover { background-color: tomato; } li.has-children:hover ul { display: block; }
 <ul> <li class="has-children"> Beelden <ul class="sub-menu"> <li>Geurkaarsen</li> <li>Rituele kaarsen</li> <li>Affirmatie kaarsen</li> </ul> </li> <li class="has-children"> Kaarsen <ul class="sub-menu"> <li>Sub-menu 2</li> <li>I don't know</li> <li>any Dutch</li> </ul> </li> <li>Wierook</li> <li>Kruiden</li> <li>Olien</li> </ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM