1

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?

5
  • 2
    Please include the code that you've tried in your question. Commented Sep 23, 2020 at 19:34
  • @Mech normally I agree. However, for this question I thought it was clearer without the code. How could the addition of non functioning code help here? Commented Sep 23, 2020 at 19:39
  • StackOverflow is meant to help you learn where you went wrong and how to fix it :) Commented Sep 23, 2020 at 19:43
  • True – but what about situations where the path forward is rather opaque? Or in this case requires functionality that apparently doesn't exist in CSS. Surely every good question doesn't need associated code Commented Sep 23, 2020 at 19:47
  • Still best to give your best attempt :) Commented Sep 23, 2020 at 20:50

4 Answers 4

3

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>

Sign up to request clarification or add additional context in comments.

2 Comments

That first answer is exactly what I was looking for. Thanks @Laif
@AlexFine No problem (: just make sure you mark answered when it allows so the question closes.
0

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!

Comments

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

div:hover { background-color: red }

Comments

-1
<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
}

1 Comment

He specified in the question that it should be done without javascript, also writing a script to accomplish something built into css is asinine. Furthermore, this code would wipe all existing classes, not just the one added on hover.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.