-3

For example, if I want the first <div> inside a <p> element, which selector would I use?

To get all <div>s in a <p> element, I would do:

p > div

in CSS.

How could I accomplish this, only getting the first <div>?

rzaaeeff
  • 850
  • 1
  • 10
  • 18
user208829
  • 15
  • 7
  • Well, you want the `first-child`, why not try the `:first-child` pseudo element? https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child – XCS Nov 29 '14 at 23:36
  • Smart! I'll go on that route. @Cristy – user208829 Nov 29 '14 at 23:43
  • 3
    FYI: A `p` can not contain `div`, that would be invalid HTML. – CBroe Nov 29 '14 at 23:53
  • You want the selector documented in the tutorial you didn't bother to read. –  Nov 30 '14 at 11:43
  • I missed it, am I not allowed to make mistakes? @torazaburo – user208829 Dec 02 '14 at 19:47
  • It's not about you being "allowed" or "not allowed" to do anything. If you missed this part of the tutorial, then you could also have googled for "CSS first child", or for the exact title of your question if you prefer. This was just a friendly suggestion for avoiding getting down-voted and having your questions closed, by doing a bit of research first before posting. –  Dec 03 '14 at 01:58

2 Answers2

0

The :first-child selector allows you to target the first element immediately inside another element.

<p>
  <div>First child...</div>
  <div>Second...</div>
  <div>Third...</div>
  <div>Fourth...</div>
</p>

In CSS:

p > div:first-child {
  font-size: 1.5em;
}

Edit: Important note is that you should never use div inside p. I wrote this code to show you how to select first child in your case, but it's really so bad to use div inside p. Whenever you use <div> between <p> and </p> like (for example) this:

<p> <div></div> </p> 

Browser will attempt to correct (to be valid code) it to this:

<p></p> <div></div> <p></p>

Good luck!

rzaaeeff
  • 850
  • 1
  • 10
  • 18
-1

If you are using p > div as the tags then the selector would be p > div:first-child

It finds p tag then the very first div.

Khaltazar
  • 296
  • 1
  • 7