TAGS :Viewed: 8 - Published at: a few seconds ago

[ css, select previous anchor ]

<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>

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}


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

Answer 1

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 }

Answer 2

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


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

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

Answer 3

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.

Answer 4

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; }