CSS
The CSS first-child
selector applies styles to the first child element of a parent element.
The CSS first-child
selector, written as :first-child
, targets the first child of a parent element.
element:first-child {
/* Styles */
}
element
: The element to target as the first child element of a parent element.:first-child
: The selector to target the first child element of the parent element.p:first-child {
font-weight: bold;
}
The first-child
selector is useful to style elements based on their position within a parent.
You can use first-child
to highlight the first item in lists, improving usability and visual hierarchy.
li:first-child {
color: blue;
font-style: italic;
}
When working with forms, you might want to style the first input field differently to draw attention or follow design requirements.
input:first-child {
border-color: green;
}
Use first-child
to give special formatting to the first paragraph in a section or article, enhancing readability.
article p:first-child {
font-size: 1.2em;
margin-top: 20px;
}
Websites often use first-child
to style the first navigation link differently, making it stand out.
nav a:first-child {
background-color: yellow;
}
In e-commerce, first-child
can emphasize the first product in a listing, indicating a featured item.
.products li:first-child {
border: 2px solid red;
}
Blogs or news sites often apply first-child
to the first element of articles to varying sections, improving navigation.
article h2:first-child {
border-bottom: 3px solid black;
}
You can also combine the first-child
selector with other classes or IDs for more specific styling.
ul.special-list li:first-child {
font-size: 1.5em;
color: purple;
}
To target elements that are not the first child, you can combine :not
with :first-child
.
ul li:not(:first-child) {
background-color: lightgray;
}
The nth-child
selector allows you to target elements based on their position within a parent element. This is useful for styling every nth element or specific children.
ul li:nth-child(3) {
color: orange;
}
This example styles the third child of each list to be orange.
Unlike first-child
, there’s no specific CSS selector for the second child. However, to target the second child of a parent element, you can use :nth-child(2)
.
ul li:nth-child(2) {
color: orange;
}
The last-child
selector targets the last child element within a parent. This is helpful for applying styles to the final element in a list or group.
ul li:last-child {
font-weight: bold;
}
The only-child
selector targets an element that is the only child of its parent. This ensures that the styles apply only when an element is the sole child.
div p:only-child {
text-align: center;
}
Understanding the difference between pseudo-classes like :first-child
and pseudo-elements like ::before
is crucial for effective CSS.
p::before {
content: "Note: ";
font-weight: bold;
}
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.