views:

16

answers:

1

Ok, I have code like this:

<div id="header"> (yeah, have to use div instead of header tag, don't ask me why)
     <a href="link"><img src="image1.png" alt="image1" /></a>
     <a href="link"><img src="image2.png" alt="image2" /></a>
     <a href="link"><img src="image3.png" alt="image3" /></a>
</div>

And I want to select the first image after div (first link image) and two last links in css.

I know I could do it by nth-child or first/last child selectors. But I want to use "+" and "~". But they doesn't seem to work!

For example:

#header + a {
     border: solid 1px red;
}

Gives border to... Nothing!

This one also doesn't seem to work:

#header a + img {
     border: solid 1px red;
}

What's wrong?

Same effect with "~". Tested in all major browsers....

+2  A: 

You've got it wrong. The selector you're looking for is

#header > a:first-child

This will select the first anchor that are direct decedent of #header. The > is the direct decedent selector, while :first-child gets you the... well, first child. To get the image, you would need

#header > a:first-child > img

The direct decendent selector is not supported in IE6. You can choose not to use it if there are no non-direct decedents you would not want to select, like with the structure you have above, which doesn't have any other anchors other than the ones you want to select.

The + is the adjacent sibling selector: http://meyerweb.com/eric/articles/webrev/200007a.html. The following HTML structure is what you would need for your selector to work:

<div id="header"></div>
<a href="#"><img src="somewhere" alt="" /></a> <-- Selects this one for #header + a
<a href="#"><img src="somewhere" alt="" /></a>
<a href="#"><img src="somewhere" alt="" /></a>
Yi Jiang
Dam! You're right. Sorry! :) BTW do I have to use ">" everywhere? Because "#header a" should work almost the same as "#header > a". I know in the first case inheritance is "deeper", but that's not a problem in this, flat anyway, code?
fomicz
@fomicz Well, if it's only one level, then no. If you can drop IE6 support, then you should try to use that as much as possible, in my opinion.
Yi Jiang