tags:

views:

52

answers:

3
+1  Q: 

CSS on anchor tags

If i have the following:

<div class="linkSet"><a href="#" class="main_link">link one a</a><a href="#" class="sub_link">link one b</a></div>

How do I set the CSS so if I hover over the first one, it changes the background colour for both anchor tags?

+6  A: 
.main_link:hover,
.main_link:hover + .sub_link {
    background-color: red;
}

However the following:

<a>
    <span class="main">...</span>
    <span class="sub">...</span>
</a>

Will give you:

  • Better structure (two links going to the same place is generally poor form as there are many interactions (tabbing, screen readers, etc) where they are treated as separate links, even if you style them so they don't)
  • Better support (Slightly old versions of MSIE don't support +)
  • Having the first link change colour when the second link is hovered (+ only works for next, there is no previous).

If the links go to different places then this isn't true, but having them right next to each other, and having them both have a hover effect when one is hovered is really user hostile as it strongly suggests that they do.

David Dorward
Ooooh, nice! What browsers does/doesn't this work in?
Pekka
Older versions of IE. I **think** support for the adjacent sibling selector was added in IE7, but I wouldn't swear to it.
David Dorward
I can't use this technique because it means that both links end up pointing to the same place. On my page, I have 2 links per row, 1 link is to add something to the database, and the other link is to remove something from the database, both for the same item related to the row the link pairs are on.
oshirowanen
I provided two techniques, the first one will still work for your use case, but I'll also refer you to back the last paragraph of my answer … and also point out that links should not perform non-idempotent (otherwise you'll have a bot or a pre-caching proxy or browser run all over your database and delete everything)
David Dorward
I've tried the first example, but it does not work. So i have updated the end of the original question to show what works a little better, but not working perfectly.
oshirowanen
The original question is showing no sign of edits, but my tests work as expected: http://dorward.me.uk/tmp/plus.html
David Dorward
A: 
a.main_link:hover, a.sub_link:hover {
    background-color: red;
}
kchau
Surely that wouldn't work? It'd turn either one of them red, when you hover over that one individually.
chigley
@chigley, Good call. My bad.
kchau
+1  A: 

If you have

<a href="first.html">Link Part A</a> <a href="second.html">Part B</a>

This CSS will highlight both when "Link Part A" is hovered, and only the second when "Part B" is hovered.

a:hover, a:hover + a {
    background-color: #fff0f0;
}

Essentially the same as David's but without using classes - there are the same issues with older IE support of the adjacent sibling selector.

Stephen P