elements specifically for :hover overriding the an

2019-03-06 01:30发布

I have code to have a background with a font color assigned with one class then have separate classes for changing the color on :hover or :active but the :active state does not trigger unless I remove the :hover specific class. 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条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-06 02:03

:active pseudo-class should go after :hover, otherwise the :hover overwrites (The order for the link-relates pseudo-clasess is: :link | :visited | :hover | :active.). You code example works as expected but if you change the classes the :active pseudo-class never applies.

.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>

You need more CSS lines but reordering the classes with :active after the :hover works fine.

.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>

查看更多
登录 后发表回答