CSS - 多个项目显示处于悬停状态的子项

时间:2017-10-27 15:34:41

标签: html css

请考虑以下代码,其中包含列表项和每个旁边的删除链接。我想拥有它,所以只有悬停的链接项显示删除按钮,而不是所有这些。请参阅下文以了解该问题:



.todo-list {
  list-style-type: square;
}

.todo-list__delete {
  display: none;
}

.todo-list:hover .todo-list__delete {
  display: inline-block;
}

<ul class="todo-list">
    <li>
      Item 1
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
    <li>
      Item 2
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
    <li>
      Item 3
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
  </ul>
&#13;
&#13;
&#13;

看起来像一个简单的问题但是什么是在CSS中定位活跃的悬停元素的最佳方法?

5 个答案:

答案 0 :(得分:4)

这样吗?

&#13;
&#13;
.todo-list {
  list-style-type: square;
}

.todo-list__delete {
  display: none;
}

li:hover .todo-list__delete {
  display: inline-block;
}
&#13;
<ul class="todo-list">
    <li>
      Item 1
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
    <li>
      Item 2
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
    <li>
      Item 3
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
  </ul>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

不要在:hover上设置.todo-list,而是在li元素上设置它。

.todo-list {
  list-style-type: square;
}

.todo-list__delete {
  display: none;
}

li:hover .todo-list__delete {
  display: inline-block;
}
<ul class="todo-list">
    <li>
      Item 1
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
    <li>
      Item 2
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
    <li>
      Item 3
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
  </ul>

答案 2 :(得分:1)

尝试在li元素上添加悬停:

.todo-list {
  list-style-type: square;
}

.todo-list__delete {
  display: none;
}

.todo-list li:hover .todo-list__delete {
  display: inline-block;
}

演示:http://jsfiddle.net/GCu2D/2205/

答案 3 :(得分:1)

:hover选择器限制为列出元素。

.todo-list {
  list-style-type: square;
}

.todo-list__delete {
  display: none;
}

.todo-list li:hover .todo-list__delete {
  display: inline-block;
}
<ul class="todo-list">
    <li>
      Item 1
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
    <li>
      Item 2
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
    <li>
      Item 3
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
  </ul>

答案 4 :(得分:1)

  

我想拥有它,只有悬停的链接项显示删除按钮

你自己有点回答了。只需使用:hover

指定项目即可

.todo-list {
  list-style-type: square;
}

.todo-list__delete {
  display: none;
}

.todo-list li:hover .todo-list__delete { /* < here */
  display: inline-block;
}
<ul class="todo-list">
    <li>
      Item 1
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
    <li>
      Item 2
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
    <li>
      Item 3
      <a class="todo-list__delete" href="#">Delete</a>
    </li>
  </ul>