oliver_siegel
oliver_siegel

Reputation: 1676

Can I target this element on hover using CSS only?

I have an i tag which I'd like to style when hovering a button tag. This is my structure:

<a class="container">
  <form>
    <button class="origin">HOVER</button>
  </form>
  <p>
    <i class="destination">TARGET</i>
    <p>
</a>

Is this possible with CSS only? (I know how to do it with JS/jQuery)

I guess I'm looking to target the cousing element here, lol...

To be more specific, I'm looking to make the TARGET text color green when hovering the button:

<style>
    a.container{ border: 1px solid black; display: block; }
    a.container:hover{border-color: red; }
    a.container:hover p i{color: yellow; }
    a form button:hover{ color: red; }
    a form button:hover p i{ color: green; } /* not working... */
    .origin:hover .destination{ color: green; } /* not working... */
</style>
<a class="container">
  <form>
    <button class="origin">HOVER</button>
  </form>
  <p>
    <i class="destination">TARGET</i>
    <p>
</a>

Upvotes: 0

Views: 500

Answers (2)

HorusKol
HorusKol

Reputation: 8696

If you only want a hover effect when you mouseover the button, then css pointer-events can do this:

.container {
    pointer-events: none;
}

.container .origin {
    pointer-events: auto;
}

.container:hover .destination {
    color: #00cc00;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events


However, since you want one hover effect when mouse over the container, and then a different one when you mouse over the button, then you're going to need to use javascript.

If you're looking for a vanilla javascript script, I've created a fiddle https://jsfiddle.net/j6hs5fmL/40/

Upvotes: 3

לבני מלכה
לבני מלכה

Reputation: 16251

You have to use jquery/js for this....

Use onmouseover and onmouseout and addClass/removeClass in css style the class

function func(){
  $(".destination").addClass("hovering");
}
function outer(){
 $(".destination").removeClass("hovering");
}
.hovering{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="container">
  <form>
    <button class="origin" onmouseover="func()" onmouseout="outer()">HOVER</button>
  </form>
  <p>
    <i class="destination">TARGET</i>
    <p>
</a>

Upvotes: 2

Related Questions