专门用于的元素:悬停覆盖等效类:active

时间:2016-07-22 13:38:19

标签: html css hover states

我的代码有一个背景,字体颜色分配了一个类,然后有单独的类来更改颜色:hover或:active但是:active状态不会触发,除非我删除:hover特定类。 CODEPEN

HTML:

<div class="backgroundRed backgroundGreenHover backgroundBlueActive" style="width: 100px; height: 100px;"></div>

CSS:

.backgroundRed, .backgroundRedHover:hover, .backgroundRedActive:active{background:red;}
    .backgroundGreen, .backgroundGreenHover:hover, .backgroundGreenActive:active{background:green;}
    .backgroundBlue, .backgroundBlueHover:hover, .backgroundBlueActive:active{background:blue;}

1 个答案:

答案 0 :(得分:1)

:active伪类应该在:hover之后,否则:hover会覆盖(链接相关伪命令的顺序是::link | :visited | :hover | :active。)。您的代码示例按预期工作,但如果您更改类,则:active伪类永远不会应用。

.backgroundRed,
.backgroundRedHover:hover,
.backgroundRedActive:active {
  background: red;
}

.backgroundGreen,
.backgroundGreenHover:hover,
.backgroundGreenActive:active {
  background: green;
}

.backgroundBlue,
.backgroundBlueHover:hover,
.backgroundBlueActive:active {
  background: blue;
}
<div class="backgroundRed backgroundBlueHover backgroundGreenActive" style="width: 100px; height: 100px;"></div>

您需要更多CSS行,但在:active正常工作后,请使用:hover重新排序这些类。

.backgroundRed,
.backgroundRedHover:hover {
  background: red;
}

.backgroundGreen,
.backgroundGreenHover:hover {
  background: green;
}

.backgroundBlue,
.backgroundBlueHover:hover {
  background: blue;
}

.backgroundRedActive:active {
  background: red;
}

.backgroundGreenActive:active {
  background: green;
}

.backgroundBlueActive:active {
  background: blue;
}
<div class="backgroundRed backgroundBlueHover backgroundGreenActive" style="width: 100px; height: 100px;"></div>