wwwww
wwwww

Reputation: 349

Menu items change their positions in html/css menu when expanding submenu

I have a simple menu made in html/css and the problem I encountered is that if I put my mouse pointer over menu item (test2) to expand submenu then other items from menu section (test1) change their positions: https://jsfiddle.net/dsb87pxz/

<nav>
  <ul>
    <li>test1</li>
    <li>
      test2
      <ul>
        <li>test2.1</li>
        <li>test2.2</li>
      </ul>
    </li>
  </ul>
</nav>


nav > ul > li {
  display: inline-block;
}

nav > ul > li > ul {
    display: none;
}

nav > ul > li:hover > ul {
    display: block;
}

nav > ul > li > ul > li {
  display: block;
}

Can you suggest a solution for this problem?

Upvotes: 0

Views: 471

Answers (4)

frnt
frnt

Reputation: 8795

That's true you just need to add vertical-align as top to your inline-block elements which are li tags here.

display:inline-block by default aligns their block text to the baseline and that's why when user hover in above codes it aligns the text to the baseline i.e. vertical-align:baseline so change that to vertical-align:top.

nav > ul > li{
  display: inline-block;
  vertical-align:top; /*Just add this as already suggested*/
}

Upvotes: 0

user3589620
user3589620

Reputation:

With vertical-align: top

nav>ul>li {
  display: inline-block;
  vertical-align: top;
}

nav>ul>li>ul {
  display: none;
}

nav>ul>li:hover>ul {
  display: block;
}

nav>ul>li>ul>li {
  display: block;
}
<nav>
  <ul>
    <li>test1</li>
    <li>
      test2
      <ul>
        <li>test2.1</li>
        <li>test2.2</li>
      </ul>
    </li>
    <li>
      test2
      <ul>
        <li>test2.1</li>
        <li>test2.2</li>
      </ul>
    </li>
  </ul>
</nav>

When you hover over a list item in the first level, it affects the list item on the right, because of display: inline-block.

Therefore one can use float: left and display: relative for <li> in the first level and display: absolute for the <ul> inside of the <li>.

Example

ul {
  list-style: none;
  padding: 0;
}

li {
  padding: 2px 5px;
}

nav>ul>li {
  float: left;
  position: relative;
}

nav>ul>li>ul {
  position: absolute;
  left: 0;
  display: none;
}

nav>ul>li:hover>ul {
  display: block;
}
<nav>
  <ul>
    <li>test1</li>
    <li>
      test2
      <ul>
        <li>test2.1</li>
        <li>test2.2</li>
      </ul>
    </li>
    <li>
      test2
      <ul>
        <li>test2.1</li>
        <li>test2.2</li>
      </ul>
    </li>
  </ul>
</nav>

Upvotes: 1

vazash
vazash

Reputation: 1

You could add position:absolute to your hover element like so

nav > ul > li:hover > ul {
display: block;
position: absolute;
}

Upvotes: 0

Dmitry T
Dmitry T

Reputation: 54

You could add position:absolute to your hover element like so

nav > ul > li:hover > ul {
    display: block;
    position: absolute;
}

Upvotes: 0

Related Questions