{"id":14184,"date":"2011-09-06T20:01:48","date_gmt":"2011-09-07T03:01:48","guid":{"rendered":"http:\/\/css-tricks.com\/?page_id=14184"},"modified":"2015-03-27T08:45:39","modified_gmt":"2015-03-27T15:45:39","slug":"first-child","status":"publish","type":"page","link":"https:\/\/css-tricks.com\/almanac\/selectors\/f\/first-child\/","title":{"rendered":":first-child"},"content":{"rendered":"

The :first-child<\/code> selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec<\/a> as a \u201cstructural pseudo-class\u201d, meaning it is used to style content based on its relationship with parent and sibling content.<\/p>\n

Suppose we have an article and want to make the first paragraph larger \u2013 like a \u201clede\u201d, or piece of introductory text:<\/p>\n

<article>\r\n  <p>First paragraph...<\/p>\r\n  <p>Lorem ipsum...<\/p>\r\n  <p>Dolor sit amet...<\/p>\r\n  <p>Consectetur adipisicing...<\/p>\r\n<\/article><\/code><\/pre>\n

Instead of giving it a class (e.g. .first<\/code>), we can use :first-child<\/code> to select it:<\/p>\n

p:first-child {\r\n  font-size: 1.5em;\r\n}<\/code><\/pre>\n

Using :first-child<\/code> is very similar to :first-of-type<\/code> but with one critical difference:<\/b> it is less specific<\/a>. :first-child<\/code> will only try to match the immediate first child of a parent element, while first-of-type<\/code> will match the first occurrence of a specified element, even if it doesn’t come absolutely first in the HTML. In the example above the outcome would be the same, only because the first child of the article<\/code> also happens to be the first p<\/code> element. This reveals the power of :first-child<\/code>: it can identify an element with relation to all its siblings, not just siblings of the same type<\/i>.<\/p>\n

The more complete example below demonstrates the use of :first-child<\/code> and a related pseudo-class selector, :last-child<\/code><\/a>.<\/p>\n

<\/code>Check out this Pen!<\/a><\/pre>\n

Other Resources<\/h3>\n