user818700
user818700

Reputation:

Selecting a specific element in CSS

Sorry about the very generic post title. But what I'm after here is this:

<div id="my-div">
   <span>
      <a href="#">link 1</a>
      <a href="#">link 2</a>
   </span>
   <a href="#">link 3</a>
</div>

How would I select 'link 3' in CSS? Without editing that Html there at all. This is the html that presented with and I need to select link 3 without selecting link 1 and 2.

Any ideas?

Upvotes: 3

Views: 2862

Answers (6)

Aleem
Aleem

Reputation: 17

It is pretty easy with Adjacent sibling selectors in CSS.

In your case you can select link 3 by using,

#my-div + a + a {
/* your CSS Rule */
}

More info can be obtained from w3c adjacent-selectors

Upvotes: 0

ProfileTwist
ProfileTwist

Reputation: 1554

#my-div span + a {
    font-size: 12px;
    line-height: 18px;
}

In this specific case I would suggest the use of an adjacent selector. Using a direct child selector ">" also works but you create the potential pitfall that if another link (i.e. link #4) was added directly after it, that link would also inherit those styles. The adjacent selector ensures that ONLY link #3 is selected even if more elements are added later on.

Upvotes: 0

Dipesh Parmar
Dipesh Parmar

Reputation: 27382

What you posted literally means "Find any a that are inside of div#my-div and are the direct child of their parent."

Use

div#my-div > a

Using the > changes the description to: "Find any a that are the direct descendents of div#my-div" which is what you want.

Upvotes: 6

Sowmya
Sowmya

Reputation: 26989

Try this

#my-div > a {
    color:red
}

DEMO

This Symbol target elements which are direct children of a parent element.

Check the more information here

Upvotes: 3

RB.
RB.

Reputation: 37222

Use the following CSS selector:

div>a

or

#my-div>a

This will select any a that is a direct descendant of a div, or the element with ID "my-div" (whichever is most appropriate to you).

E.g.

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        div>a 
        {
            color:Red;
        }

        #my-div>a 
        {
            color:Blue;
        }
    </style>
</head>
<body>
    <div id="my-div">
   <span>
      <a href="#">link 1</a>
      <a href="#">link 2</a>
   </span>
   <a href="#">link 3 (this will be blue as per CSS)</a>
</div>
</body>
</html>

Upvotes: 3

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

#my-div>a{
  background: red;
}

Upvotes: 1

Related Questions