The :first-child
selector matches the first child element.
:first-child
is a Pseudo-class and it
applies to any element that is the first child of another element.
With :first-child
pseudo-class, an element
is matched only when it is the first child of another element.
For example, p:first-child
will select any p element that is the first child of some other element.
It does not select whatever element is the first child of a paragraph; for that, we can
use p > *: first-child
.
Examples:
body *:first-child {font-weight: bold;} p:first-child {font-size: 125%;}
:first-child { style properties }
:first-child |
Yes | 7.0 | Yes | Yes | Yes |
An example showing how to use :first-child CSS selector.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style type="text/css">
:first-child { <!-- www.j av a 2 s . c om-->
border: thin black solid;
padding: 4px;
}
</style>
</head>
<body>
<p>I like <span>HTML</span> and <span>CSS</span>.</p>
</body>
</html>
We can use the :first-child
selector as
a modifier and combining it with other selectors.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style type="text/css">
p > span:first-child { <!-- w w w . j a v a 2s . co m-->
border: thin black solid;
padding: 4px;
}
</style>
</head>
<body>
<p>I like <span>HTML</span> and <span>CSS</span>.</p>
</body>
</html>
In the following example, the selector matches the first <i>
element in all <p>
elements:
<html>
<head>
<style>
p > i:first-child<!-- w w w. j a va 2s .c om-->
{
font-weight:bold;
}
</style>
</head>
<body>
<p>HTML is <i>easy</i>. CSS is <i>easy</i>.</p>
<p>HTML is <i>easy</i>. CSS is <i>easy</i>.</p>
</body>
</html>
In the following example,
the selector matches all <i>
elements in <p>
elements that are the first child of another element.
<html>
<head>
<style>
p:first-child i<!--from w w w . j a v a 2 s. c o m-->
{
color:blue;
}
</style>
</head>
<body>
<p>HTML is <i>easy</i>. CSS is <i>easy</i>.</p>
<p>HTML is <i>easy</i>. CSS is <i>easy</i>.</p>
</body>
</html>