Home >Web Front-end >CSS Tutorial >CSS3: How to use the first-child selector

CSS3: How to use the first-child selector

青灯夜游
青灯夜游Original
2019-05-31 11:54:144338browse

CSS: The first-child selector is used to match the first child element in its parent element; that is, an element will be matched only if it is the first child element of its parent element.

CSS3: How to use the first-child selector

CSS3: How to use the first-child selector?

#: The first-child selector matches the first child element within its parent element.

Syntax:

元素:first-child
{ 
css样式
}

Example: Match the first

element of the parent element of

p:first-child
{ 
    background-color:yellow;
}

Note: All major browsers support the :first-child selector. For :first-child in IE8 and earlier browsers, must be declared.

CSS :first-child selector usage example

##Example 1:Select each

and set its style for each element in which the

element is the first child element of its parent element:

<!DOCTYPE html>
<html>
<head>
<style>
p:first-child i
{
background:yellow;
}
</style>
</head>
<body>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
</body>
</html>

Rendering:


CSS3: How to use the first-child selector

Example 2:The style selected for the first child element of each

    element
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<style>
ul>:first-child
{
background:yellow;
}
</style>
</head>
<body>
<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Coca Cola</li>
</ul>
<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Coca Cola</li>
</ul>
</body>
</html>

Rendering:


CSS3: How to use the first-child selector

The above is the detailed content of CSS3: How to use the first-child selector. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn