Jason
Jason

Reputation: 1309

Selecting just one child using CSS3

I have a simple CSS3 question regarding to selecting appropriate child node.

Here is a snippet of current HTML element structure:

<nav>
    <ul>
        <li>
            <a href="#"><div class="adminNavButton"><p>Pages</p></div></a>
            <ul>
                <li><a href="#">Make a new page</a></li>
                <li><a href="#">Manage pages</a></li>
                <li><a href="#">Delete pages</a></li>
            </ul>
        </li>
and more .... </ul> </nav>

In CSS3, I'm trying to select just <a href="#"><div class="adminNavButton"><p>Pages</p></div></a> using

nav ul li a{
}

However, it selects every children anchor tags including ones under <ul><li>. Do I have to give it a class selector to solve the issue? i.e.

<nav>
    <ul>
        <li>
            <a class="something" href="#"><div class="adminNavButton"><p>Pages</p></div></a>

If you know a technique that works across all browsers, I would appreciate it if you could share it with me.

Thanks in advance,

================================= Thanks for all your comments guys, :first-child nor :nth-child(1) didn't work from my main project so I've created a new project and tested the method. But it did not work So here is HTML structure and CSS3.

<!DOCTYPE html>

<html>

<head>
    <meta charset="UTF-8">
    <title>asf</title>
    <style>
        ul li a:first-child{
            color: red;
        }
    </style>
</head>

<body>
    <ul>
        <li>
            <a href="">asf</a>
            <div>
                <a href="">asf</a>
            </div>
        </li>
        <li>
            <a href="">asfd</a>
            <div>
                <a href="">asf</a>
            </div>
        </li>
        <li>
            <a href="">asf</a>
            <div>
                <a href="">asf</a>
            </div>
        </li>
    </ul>
</body>


</html>

hmm heh =/ (p.s. I've tested it on Firefox and Chrome browser but didn't work)

Upvotes: 2

Views: 99

Answers (2)

Paul Dessert
Paul Dessert

Reputation: 6389

This should do the trick:

nav ul li a:first-child{
}

You can also use a class, but if the structure will remain the same (in the first position) the example above is the best route.

Upvotes: 0

MrCode
MrCode

Reputation: 64526

You can use the first-child Pseudo-class:

nav > ul > li > a:first-child
{

}

Another option that will do what you want is the > selector:

nav > ul > li > a
{

}

The above will only apply to the Pages anchor. The > is the child selector so the element must be a direct child, unlike when using a space which targets all descendants. If you have siblings of Pages then those siblings would also be targeted whereas the first example wouldn't.

jsFiddle demo

From the W3C docs:

The :first-child pseudo-class represents an element that is the first child of some other element. Same as :nth-child(1).

Upvotes: 1

Related Questions