turtle
turtle

Reputation: 8103

Link styling only specific links in a list

I have a list CSS style that looks like this:

.my-list {
    text-align: center;
    list-style: none;
    a { color: #000000; }
}

I would like to style the color of certain links inside this list with another color. How can I do this?

<li class=my-list>

    <a href="www.blah.com">this link is black</a>

    <a href="www.blahblah.com">I WANT THIS LINK TO BE ANOTHER COLOR</a>

</li>

I would like a CSS solution to this problem that does not require manually changing the link color. I have many of these lists, and a manual solution is not feasible.

Upvotes: 2

Views: 1023

Answers (5)

Darren
Darren

Reputation: 70814

You want to add a after mylist to indicate you want to apply this CSS to a tags. You could use pseudo selectors, first-child, nth-child to select specific tags within the list:

.my-list a {
    background-color : #000000; 
}

Using the first-child pseudo selector.

.my-list a:first-child {
    background-color: red;
}

To select the 2nd link in your list

Use the nth-child selector:

.my-list a:nth-child(2) {
    background-color: red;
}

http://jsfiddle.net/6JSSJ/

Upvotes: 1

mars
mars

Reputation: 40

You can add an addtional CSS class or use the attribute selector http://css-tricks.com/attribute-selectors/

Upvotes: 0

Ben McCormick
Ben McCormick

Reputation: 25728

Add a class to the links that you want a different color:

.my-list {
    text-align: center;
    list-style: none;
}

.my-list a.diffcolor {
    color:red

}

Then you can just mark the ones you want to have that color with the class.

<li class=my-list>

    <a href="www.blah.com">this link is black</a>

    <a href="www.blahblah.com" class="diffcolor">I WANT THIS LINK TO BE ANOTHER COLOR</a>

</li>

Upvotes: 1

James Coyle
James Coyle

Reputation: 10428

Use:

.my-list {
  //some styles here
}
.my-list a {
  //some styles for links here
}

You cannot nest CSS within blocks, it is not like a programming language. The only case where you nest a block within another is for defining media queries.

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

Use nth-child CSS3 selector to select <a> element by it's index within <li>:

.my-list a:nth-child(2) {
    color: red;
}

Sample: http://jsfiddle.net/6hCWY/

Upvotes: 2

Related Questions