chris
chris

Reputation: 597

.class a:hover vs .class:hover a

Couldn't find an answer to something I've been wondering about.

Is there a difference between .class2 a:hover {} and .class2:hover a {}? Or a preference for one over the other?

I've been using .class2 a:hover {} to alter anchors on anchor hover (ie: anchor text color), but when I wanted to alter the div that held the anchor as well (ie: anchor color and div background-color both change on hover), I had to use .class2:hover a {} for it to work. In doing so, I got confused as to the difference because between the two as they are written so similarly.

Thanks!

EDIT
Edited the question to be more clear. Thanks for untwisting my brain :)

Upvotes: 2

Views: 14087

Answers (5)

Jacob Reisner
Jacob Reisner

Reputation: 162

In class2:hover, you're activating the CSS class under all elements nested in the class. This includes if you wanted to add padding outside the border of your links.

In class2 a:hover, the CSS class is only activated when you're hovering specifically over the link. Otherwise, the class is ignored.

Hope this helps!

Upvotes: 0

justinw
justinw

Reputation: 3976

My understanding is this:

.class2 a:hover will target any hyperlink tags within .class2 elements when the a tags are hovered.

.class2:hover a will target any hyperlink a tags within .class2 elements when .class2 is hovered.

The distinction is which element you hover in order to change those styling rules.

Example:

.box{
  background: red;
  width: 50px;
  height: 50px;
  margin-bottom: 10px;
}
.case1 a:hover {
  background: blue;
}  

.case2:hover a {
   background: green;
}
<html>
  <body>
    <div class="box case1"><a href="#">case 1</a></div>
    <div class="box case2"><a href="#">case 2</a></div>
  </body>
</html>

In this case, do you want to hover the .class2 element or the a?

Upvotes: 9

Rezwan Azfar Haleem
Rezwan Azfar Haleem

Reputation: 1228

.class:hover a selects the a link when any part of the class is hovered upon while .class a:hover selects the a link only when the a link is hovered upon

Upvotes: 0

KiiroSora09
KiiroSora09

Reputation: 2287

.class2 a:hover {}

With the above, the style would only apply to a when the a element is hovered specifically, if the .class element has padding or other content, hovering over the other parts of the .class element will not trigger the hovered style for a


.class2:hover a {}

While the above will trigger the hover style for a if any part of the .class2 element is hovered (padding, content, etc..)

Working fiddle here.

Upvotes: 1

ded
ded

Reputation: 1350

Yes. There is a difference.

Behaviorally, there may not seem like a difference, but if you add a margin around your <a> tag, you might find that your first selector (.class2 a:hover {}) will stop working as indended.

Upvotes: 0

Related Questions