Using the :first-child Selector

Description

The :first-child selector will match elements that are the first element defined by its parent element.

Example

The following code uses the :first-child Selector.


<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
:first-child {<!--   w w  w.  ja  v a2  s.c  o m-->
  border: thin black solid;
  padding: 4px;
}
</style>
</head>
<body>
  <a href="http://java2s.com">Visit the website</a>
  <p>
    I like <span>CSS</span> and <span>HTML</span>.
  </p>
  <a href="http://w3c.org">Visit the W3C website</a>
</body>
</html>

Click to view the demo

The code above used the :first-child selector on its own, meaning that it will match any element that is the first child of its containing element.

Example 2

The following code combines the :first-child Selector with Other Selectors.


<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
p>span:first-child {
  border: thin black solid;
  padding: 4px;
}<!--   w  w w.  j a v  a2  s .c o m-->
</style>
</head>
<body>
  <a href="http://java2s.com">Visit the website</a>
  <p>
    I like <span>CSS</span> and <span>HTML</span>.
  </p>
  <a href="http://w3c.org">W3C</a>
</body>
</html>

Click to view the demo

This selector will match any span element that is the first child of a p element.





















Home »
  HTML CSS »
    CSS »




CSS Introduction
CSS Background
CSS Border
CSS Box Layout
CSS Text
CSS Font
CSS Form
CSS List
CSS Selectors
CSS Others
CSS Table