Reputation:
<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>
Upvotes: 1
Views: 1798
Reputation: 394
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; }
Upvotes: 0
Reputation: 2178
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.
Upvotes: 0
Reputation: 25435
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
Upvotes: 1
Reputation: 4946
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>
Upvotes: 2