[css] How do I add a new class to an element dynamically?

Is there any way to add a new CSS class to an element on :hover?

Like for jQuery, but translated into CSS:

$(element).addClass('someclass');

This question is related to css addclass

The answer is


:hover is a pseudoclass, so you can put your CSS declarations there:

a:hover {
    color: #f00;
}

You can also use a list of selectors to apply CSS declarations to a hovered element or an element with a certain class:

.some-class,
a:hover {
    color: #f00;
}

Using CSS only, no. You need to use jQuery to add it.


This is how you do it:

var e = document.getElementById('myIdName');
var value = window.getComputedStyle(e, null).getPropertyValue("zIndex");
alert('z-index: ' + value);

Yes you can - first capture the event using onmouseover, then set the class name using Element.className.

If you like to add or remove classes - use the more convenient Element.classList method.

_x000D_
_x000D_
.active {
  background: red;
}
_x000D_
<div onmouseover=className="active">
  Hover this!
</div>
_x000D_
_x000D_
_x000D_


Since everyone has given you jQuery/JS answers to this, I will provide an additional solution. The answer to your question is still no, but using LESS (a CSS Pre-processor) you can do this easily.

.first-class {
  background-color: yellow;
}
.second-class:hover {
  .first-class;
}

Quite simply, any time you hover over .second-class it will give it all the properties of .first-class. Note that it won't add the class permanently, just on hover. You can learn more about LESS here: Getting Started with LESS

Here is a SASS way to do it as well:

.first-class {
  background-color: yellow;
}
.second-class {
  &:hover {
    @extend .first-class;
  }
}

why @Marco Berrocl get a negative feedback and his answer is totally right what about using a library to make some animation so i need to call the class in hover to element not copy the code from the library and this will make me slow.

so i think hover not the answer and he should use jquery or javascript in many cases


CSS really doesn't have the ability to modify an object in the same manner as JavaScript, so in short - no.