views:

27

answers:

4
<ul class="list">
    <li><a href="">Text 1</a></li>
    <li><a href="">Text 2</a></li>
    <li><a href="" class="selected">Text 3</a></li>
</ul>

how do I select the anchor for Text 2 without adding an extra class? (and no javascript)

<style type="text/css">
    ul.list li a.selected ******{background-color:#000}
</style>

output:

<li><a href="" style="background-color:#000;">Text 2</a></li>
+2  A: 

Without javascript your results will not always work across each browser. Check this link by sitepoint

This is the way it would be done using CSS3, This pesudo-class is currently not supported in Internet Explorer.

<style type="text/css">
ul.list li:nth-child(2) a { background:#000 }
</style>
Jon Harding
+1  A: 

the nth child selector can do this. browser support varies.

try:

ul.list li:nth-child(2) a { background:#000; }

Ref: http://reference.sitepoint.com/css/pseudoclass-nthchild

Moin Zaman
+1  A: 

It seems like you're looking for a previous sibling selector, which unfortunately doesn't exist. See this post for useful links on what is possible.

misterkeg
that sucks. but thanks! :)
A: 

I don't think there's any way to simply select *th child element. (Except firstChild element, which let you specify the first child element.) But alternatively you can consistently assign numbered ID's to li element, for example

<li id="1"><a href="">Text 1</a></li>
<li id="2"><a href="">Text 2</a></li>
<li id="3"><a href="">Text 3</a></li>

Then you can use that to specify *th li element using the value in id attribute. So your css should be

ul.list li[id="2"] a { background-color: #000; }
djrsargent