contact@codebetter.in 8823075444
9993928766
  • Tutorials Home
  • Contact

How do you apply CSS styles to only the first child or last child of an element?

first child: The first-child is a pseudo-class in CSS that represents the first element among a group of sibling elements. The:first-child Selector is used to target the first-child element of its parent for styling.
Example:
<html>
<head>
<style>
ul li:first-child {
color: blue;
font-weight: bold;
}
</style>
</head>
<body>
<ul>
<li>This is the first list item (blue).</li>
<li>This is the second list item.</li>
<li>This is the third list item.</li>
</ul>
</body>
</html>
Output:
  • This is the first list item (blue).
  • This is the second list item.
  • This is the third list item.

last child:The last-child selector allows us to select the last element inside a set of siblings’ elements within its defining element. the last-child selector is a pseudo-class that chooses the final member of the siblings in the block that contains it.
Example:
<html>
<head>
<style>
p:last-child {
background-color: #e5aaaa;
}
</style>
</head>
<body>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</body>
</html>
Output:

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.