【问题标题】:How do you properly apply hover css to <li> elements with list-style-type: none?如何正确地将悬停 css 应用于具有 list-style-type: none 的 <li> 元素?
【发布时间】:2015-04-21 01:33:15
【问题描述】:

我有一个列表,每个列表项都有两个锚标记,一个向左浮动,另一个向右浮动。当包含元素的 list-style-type 是 disc 时,在两个元素之间悬停可以按我的预期工作。但是,如果将 list-style-type 更改为 none,则当您将鼠标悬停在元素之间时,li:hover css 似乎并不适用。

我已在最新版本的 Chrome、Firefox 和 Internet Explorer 中确认了该问题。

ul{
    list-style-type: disc;
    /* Replace the previous line with the one below.
        The hover styling no longer applies when the cursor is between anchor tags. */
    /* list-style-type: none; */
}

li{
    clear:both;
}

.left{
    float: left;
}

.right{
    float: right;
    opacity: 0;
}

li:hover > a{
    text-decoration: underline;
    opacity: 1 !important;
}
<ul>
    <li>
        <a class="left">Option 1</a>
        <a class="right">Only</a>
    </li>
    <li>
        <a class="left">Option 2</a>
        <a class="right">Only</a>
    </li>
</ul>

https://jsfiddle.net/thomaslangston/xh7r9b68/

【问题讨论】:

  • 似乎正在为我工​​作:/
  • 我正在使用 Firefox,为我工作。与光盘具有或不具有样式的相同功能。你用的是什么浏览器?
  • 我使用的是 Chrome,但我刚刚在 Firefox 中进行了测试,并确认它在那里的工作方式也有所不同。
  • 我可以在 Firefox 中确认该问题,因此该问题是可以验证的。
  • 下划线对我来说适用于 chrome。我仍然看到文字后面的文字装饰。可以直接在a标签上添加悬停效果吗?

标签: css


【解决方案1】:

这个问题很有趣。在您的 sn-p 中,您浮动两个子元素,因此它们被从常规内容流中取出。

在第一个示例中,显示了一张光盘,li 有内容,因此您可以越过某个高度。

如果您取出设置list-style-type: none,子弹/圆盘就消失了,li 现在的高度为零,因此悬停不会做任何事情。

如果为li 添加边框,这会更清楚。您可以通过将overflow: auto 添加到li 以包含浮动来解决此问题,以便li 保持非零高度。

请看下面的两个例子,第一个显示光盘,第二个没有。

请注意,如果您添加边框,则如果您在边框本身上移动,则会激活悬停(需要一些精确的鼠标定位)。

ul.ex1 {
list-style-type: disc;
}
ul.ex2 {
list-style-type: none;
}
li {
  clear: both;
  border: 1px dotted gray;
}
ul.ex2 li {
  overflow: auto;
}
.left {
  float: left;
}
.right {
  float: right;
  opacity: 0;
}
li:hover > a {
  text-decoration: underline;
  opacity: 1 !important;
}
<ul class="ex1">
  <li>
    <a class="left">Option 1</a>
    <a class="right">Only</a>
  </li>
  <li>
    <a class="left">Option 2</a>
    <a class="right">Only</a>
  </li>
</ul>

<ul class="ex2">
  <li>
    <a class="left">Option 1</a>
    <a class="right">Only</a>
  </li>
  <li>
    <a class="left">Option 2</a>
    <a class="right">Only</a>
  </li>
</ul>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    相关资源
    最近更新 更多