Search code examples
htmlcssz-index

Trying to make div appear on top of scrollable list of content but relative to list item


I have a list of items inside a div. The list is scrollable on the Y-axis but not the X-axis.

The end-goal is to have another div that will appear when clicked (context menu), it shall appear on top of and overflow/ignore the width restrictions of the div and it must be relative to the list item.

See the attached sample where a #contextMenu is hardcoded into list item 7.

The #contextMenu content is restricted by the X-axis width of the parent div, it should be on top of this.

#parent {
  width: 150px;
  height: 100px;
  overflow-x: hidden;
  overflow-y: scroll;
position: relative;

}

.listItem {
}

#contextMenu {
  z-index: 999;
  position: absolute;
  background-color: #ffffff;
  border: 1px solid rgb(165, 165, 165);
  width: 200px;
  padding: 2px;
  display: block;
  margin: 0;
  list-style-type: none;
  list-style: none;
}
<div id="parent">
  <ul>
    <li class="listItem">List item 1</li>
    <li class="listItem">List item 2</li>
    <li class="listItem">List item 3</li>
    <li class="listItem">List item 4</li>
    <li class="listItem">List item 5</li>
    <li class="listItem">List item 6</li>
    <li class="listItem">List item 7
      <div id="contextMenu">
        <p> Menu item 1</p>
        <p> Menu item 2</p>
        <p> Menu item 3</p>
      </div>
    </li>
    <li class="listItem">List item 8</li>
    <li class="listItem">List item 9</li>
    <li class="listItem">List item 10</li>
  </ul>

</div>


Solution

  • Because contextMenu is a child element, it will always be relative to its parent's z-index. It remains nested. If I understand correctly, you want contextMenu to appear on top of the #parent div - this can't be accomplished while it's a child. Most likely you'll need to use javascript to create a new element on the list item's position when clicked.