为什么不透明度声明的顺序在这个两阶段淡入中很重要?

Why is the order of opacity declaration important in this two-phase fade-in?

我写了一个两相淡入淡出的按钮。我注意到声明不透明度状态的顺序很重要。

这个CSS有效:

.item .btn-remove {
  transition: opacity 0.5s ease-in-out;
  opacity: 0;
}

.item:hover .btn-remove {
  opacity: .25;
}

.item .btn-remove:hover {
  /* works here */
  opacity: 1;
}

与不起作用的版本:

.item .btn-remove {
  transition: opacity 0.5s ease-in-out;
  opacity: 0;
}

.item .btn-remove:hover {
  opacity: 1;
}

.item:hover .btn-remove {
  opacity: .25;
}

我可以看出声明的顺序是有道理的,但不明白为什么这会有所不同,因为规则并不冲突(据我对 CSS 的理解)。

请参阅我的 fiddle 示例。

匹配 :hover 的元素的所有祖先也将匹配 :hover。虽然 :hover 是一个 CSS 选择器,但这是在 HTML 规范中指定的,而不是选择器。来自 section 4.14.2 of W3C HTML5:

The :hover pseudo-class is defined to match an element "while the user designates an element with a pointing device". For the purposes of defining the :hover pseudo-class only, an HTML user agent must consider an element as being one that the user designates if it is:

  • An element that the user indicates using a pointing device.

  • An element that has a descendant that the user indicates using a pointing device.

因此,即使 .btn-remove 本身匹配 :hover(即当 .btn-remove 是指定的元素时),.item:hover .btn-remove 规则仍然适用。换句话说,这两个 CSS 规则实际上相互重叠,因此产生了冲突。