Alex Fine
Alex Fine

Reputation: 149

Add CSS Class OnHover in CSS

When I hover over an HTML element I would like that element to inherit the properties of a pre-written CSS class.

Is there a way to accomplish this task without Javascript?

Upvotes: 1

Views: 2162

Answers (4)

Aman Patel
Aman Patel

Reputation: 1

Hover Me Hover Me That would add / remove the class name with javascript, otherwise do this in CSS:

div:hover { background-color: red }

Upvotes: 0

ciphermode00
ciphermode00

Reputation: 11

In your CSS file, write a hover selector for the element you are targeting:

a {
text-decoration: none;
}

a:hover {
text-decoration: underline;
color: red;
}

Creating the :hover selector will inherit the properties associated when the mouse hovers over the selected element.

<div>
    <a href="#">Example 1</a>
</div>

Hope that answers your question!

Upvotes: 0

Devin McQueeney
Devin McQueeney

Reputation: 1287

<div mouseover="this.className='myClass'" onmouseout="this.className=''">
Hover Me
</div>

That would add / remove the class name with javascript, otherwise do this in CSS:

div:hover {
background-color: red
}

Upvotes: -1

Libra
Libra

Reputation: 2595

Write a hover class for an item, which does the exact same thing that you are describing.

.box{
  height: 60px;
  width: 60px;
  border: 1px solid black;
  margin: 20px;
}

.box1:hover, .box2{
  background-color: red;
}
<div class="box box1"></div>
<div class="box box2"></div>

More simply:

.box{
  height: 60px;
  width: 60px;
  border: 1px solid black;
  margin: 20px;
}

.box:hover{
  background-color: red;
}
 <div class="box"></div>

Upvotes: 3

Related Questions