Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are my divs all displaying in the same location on hover?

Tags:

html

css

flexbox

I would like to create a top menu. I have created this which gets the components to become visible when they have to, but my problem is that I don't know how to get each menu-sub-item to display under the hovered button.

body {
  margin: 0
}

.menu {
  height: 20px;
  width: 100vw;
}

.menu-main-item:hover+.menu-sub-item {
  display: flex;
  position: absolute;
  top: 20px;
}

.menu-sub-item {
  display: none;
  z-index: 1;
  flex-direction: column;
}

.menu-sub-item:hover {
  display: flex;
  position: absolute;
  top: 20px;
}
<div class="menu">
  <button class="menu-main-item">This is 1</button>
  <div class="menu-sub-item">
    <button>Sub 1.1</button>
    <button>Sub 1.2</button>
    <button>Sub 1.3</button>
  </div>
  <button class="menu-main-item">Ok 2</button>
  <div class="menu-sub-item">
    <button>Sub 2.1</button>
    <button>Sub 2.2</button>
    <button>Sub 2.3</button>
  </div>
  <button class="menu-main-item">Another 3</button>
  <div class="menu-sub-item">
    <button>Sub 3.1</button>
    <button>Sub 3.2</button>
    <button>Sub 3.3</button>
  </div>
</div>
like image 317
Frank Avatar asked Dec 14 '25 04:12

Frank


1 Answers

I would use an unordered list (turning your .menu element into a ul) so you can position the .menu-sub-item element relatively to its list-item.

you need to set position: relative to the li element, and white-space: nowrap to the buttons, so the caption will overflow their container.

body {
  margin: 0
}

.menu {
  height: 20px;
  width: 100vw;
  margin: 0;
  padding: 0;
  display: flex;
  list-style: none;
}

.menu li { position: relative; }

.menu button { 
  text-align: left;
  white-space: nowrap; }


.menu-main-item:hover+.menu-sub-item {
  display: flex;
  position: absolute;
  top: 20px;
}

.menu-sub-item {
  display: none;
  z-index: 1;
  flex-direction: column;
}

.menu-sub-item:hover {
  display: flex;
  position: absolute;
  top: 20px;
}
<ul class="menu">
  <li>
    <button class="menu-main-item">This is 1</button>
    <div class="menu-sub-item">
      <button>Sub 1.1</button>
      <button>Sub 1.2</button>
      <button>Sub 1.3</button>
    </div>
  </li>
  <li>
    <button class="menu-main-item">Ok 2</button>
    <div class="menu-sub-item">
      <button>Sub 2.1 and some other text</button>
      <button>Sub 2.2</button>
      <button>Sub 2.3</button>
    </div>
  </li>
  <li>
    <button class="menu-main-item">Another 3</button>
    <div class="menu-sub-item">
      <button>Sub 3.1</button>
      <button>Sub 3.2</button>
      <button>Sub 3.3</button>
    </div>
  </li>
</ul>
like image 134
Fabrizio Calderan Avatar answered Dec 16 '25 19:12

Fabrizio Calderan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!