CSS style first node
CSS Style First Node
In CSS, we often encounter situations where we need to set special styles for the first node in a document. For example, in a list, we might want to style the first item, or the first word in a paragraph. We can use the :first-child
pseudo-class in CSS selectors to style the first node.
1. Selector: :first-child
The :first-child
pseudo-class selector is used to select the first child element of an element. Its syntax is as follows:
selector:first-child {
/* styles */
}
Where selector
is the parent element selector of the element to be selected, which can be a tag name, class name, ID, etc.
2. Styling the First Node Example
2.1 Styling the First List Item in a List
Suppose we have an unordered list and want to apply special styles to the first list item. We can use the :first-child
pseudo-class selector to achieve this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Style First Node Example</title>
<style>
ul li:first-child {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
</ul>
</body>
</html>
In the example above, we apply red and bold styles to the ul li:first-child
selector, giving the first list item a different style than the other list items.
2.2 Styling the First Word in a Paragraph
Similarly, we can also apply special styling to the first word in a paragraph.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Style First Node Example</title>
<style>
p:first-child::first-letter {
font-size: 24px;
color: blue;
}
</style>
</head>
<body>
<p>This is an example paragraph with special styling applied to the first letter. </p>
</body>
</html>
In the example above, we use the :first-letter
pseudo-element selector to select the first letter and apply a blue color and a larger font size. This will give the first word in a paragraph a special style.
3. Summary
By using the :first-child
pseudo-class selector, we can easily style the first node in a document, achieving better page presentation. In practice, we can flexibly apply the :first-child
selector as needed to add more creativity and highlights to page designs.