开发者

Selecting only the first specifically-typed child of an element

I want to select the first child of <body> that is a <div>, and only that element.

I'm having trouble formulating the right selector for the element I want. I could simply give it an ID, but now I'm curious about whether this is possible in general.

In a simple situation like this:

<body>
  <div></div>
</body>

I can just use the child selector:

body > div {
    margin: 0 auto 0 auto;
    width: 800px;
}

But what happens now if there are two <div> elements underneath <body>?

<body>
  <div></div>
  <div></div>
</body>

Well, now I can just use the first-child pseudo-class to make my selection. This wo开发者_Python百科rks great:

body > div:first-child {
    margin: 0 auto 0 auto;
    width: 800px;
}

But wait just a second. What if someone goes and sticks another child element into <body> before my <div>?

<body>
  <a name="top"></a>
  <div></div>
  <div></div>
</body>

How can I select only the first <div> child in this case (in general)?


Try the first-of-type selector

body > div:first-of-type
{
    margin: 0 auto 0 auto;
    width: 800px;
}

[Edit] Check out nth-of-type while you're at it.

[Edit] Added a child selector.


It seems to me first-of-type does the job.


:first-child will only select something if it is the first child of its parent

:first-of-type will work however support for this is fairly recent and won't work on older browsers (read IE): http://reference.sitepoint.com/css/pseudoclass-firstoftype

Depending on what you want to support, or how complex your code is, you may have to fall back to giving your div a class.


If you have a probability that "someone goes and sticks another child" then you have no other options other than giving it an ID.

For example if you have a <div> and someone will insert another <div> before yours then no existing CSS selectors would work for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜