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

4 Answers4

2

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
  • 4,928
  • 13
  • 51
  • 96
1

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
  • 25,281
  • 6
  • 70
  • 74
0

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.

Community
  • 1
  • 1
keirog
  • 2,158
  • 1
  • 19
  • 17
0

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
  • 394
  • 2
  • 4