-2

Let's say I have a list of items in a container with some padding around them. When I hover over one of the items in that list, I want a "delete" icon to appear in the padding/margin to the right of the item. The problem is, if this the hover event is on the item itself, the delete icon will disappear as soon as you try to click it because you will have stopped hovering on the item. How can I design this so I will not lose the icon when moving the mouse to click on it?

EDIT: My code is in React, so I've provided a simple hypothetical example here:

<div class="container">
  <div class="item">

  </div>
  <i class="icon" />
  <div class="item">

  </div>
  <i class="icon" />
  <div class="item">

  </div>
  <i class="icon" />
</div>

.container {
  display: flex;
  padding: 24px;
}

.icon {
  display: none;
}

.item:hover~.icon {
  display: block;
}

EDIT2: I made sure the icon was inside the container, but now it's getting cut off: enter image description here

ipenguin67
  • 1,483
  • 5
  • 22
  • 39

2 Answers2

0

If the hover is set in CSS, make sure the icon is inside the element that the hover is set on:

// HTML
<div class="container">
   <div class="item">
      <img src="delete.png"/>
   </div>
</div>

// CSS
.item:not(:hover) img {
    display: none;
}
Emre Koc
  • 1,481
  • 10
  • 18
  • Thanks, I tried this but now the icon is getting hidden behind the padding even with a high z-index (see image in EDIT2) – ipenguin67 Jul 22 '20 at 11:48
  • Is there an `overflow: hidden;` on the item? You could wrap the item with another div, set the hover on that, place the item itself in there and the icon next to it (same level, as siblings). Then put the overflow on the item. – Emre Koc Jul 22 '20 at 11:52
  • There's an overflow-y on the entire list, but not any overflow set on the items themselves. – ipenguin67 Jul 22 '20 at 11:58
  • Unfortunately, there is no way to have both an overflow on the container, and not clip the icon inside of it, as you cant use `overflow-x: visible` or something (as seen here https://stackoverflow.com/questions/6421966/css-overflow-x-visible-and-overflow-y-hidden-causing-scrollbar-issue) – Emre Koc Jul 22 '20 at 12:07
  • I ended up using the hack in that linked article of setting the same positive padding as negative margin and that seemed to work. – ipenguin67 Jul 22 '20 at 18:09
0

It sounds like you have the :hover rule on the wrong element. You need to define the style so it shows the button when it hovers the common parent of the item and the button. That way you can move the cursor to the button without it being hidden.

(I also recommend using visibility: hidden; instead of display: none; so the layout doesn't change when you hover.)

<ul>
  <li>Item <button>Delete</button></li>
  <li>Item <button>Delete</button></li>
  <li>Item <button>Delete</button></li>
</ul>
li:not(:hover) > button {
  visibility: hidden;
}

Codepen: https://codepen.io/arnemahl/pen/bGEzoVz

ArneHugo
  • 6,051
  • 1
  • 26
  • 47