CSS first-child Selector Tutorial with Examples – POFTUT

CSS first-child Selector Tutorial with Examples

We can select the first child of the given HTML element in different ways. But CSS provides the first-child attribute in order to select the first child of the given HTML element. We will also learn nth-child to select the first child.

first-child Syntax

The first-child CSS attribute syntax is like below.

  • HTML_ELEMENT is the element type of element we want to select its first child.
  • :first-child is the CSS selector for the first child.
  • CSS_CODE is the CSS attributes we want to apply to the given first child elements.

Select First Child with first-child CSS

We will use  first-child of the given HTML elements. We will set every first child background color to the yellow. In the example, we will set the body first element and div’s first elements background color to the yellow.

Select First Child with first-child CSS

Select First Child with first-child CSS

Select First Child with nth-child CSS

nth-child is another CSS selector that can be used to select the first child of the given HTML element. nth-child() works like a function where we will provide the child order number to the nth-child selector which will be 1 in this case.

LEARN MORE  CSS :nth-child Element Selector

Select First Child with nth-child CSS

Select First Child with nth-child CSS

Select First Child HTML Element of the Given HTML Element

Select First List Item

We can use the first-child in order to select the first item of a list.

LEARN MORE  CSS :nth-child Element Selector

Select First List Item

Select First List Item

Select First Div

We can also select the first div of the HTML elements.

Select First Div

Select First Div

Select Last Child HTML Element with CSS last-child

CSS also provides the last-child selector which will select the last child of the given HTML element and apply given CSS.

Select Last Child HTML Element with CSS last-child

Select Last Child HTML Element with CSS last-child

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)