CSS selector last
CSS Selector Last
In CSS, selectors are a way to select elements in an HTML document. By using different selectors, we can apply styles to specific elements, thereby achieving page layout and aesthetics.
This article will focus on a special selector in CSS—the last selector. The last selector is used to select the last element among elements that meet the conditions.
What is the last selector?
The last selector in CSS is represented by :last-of-type
. This selector selects the last element that meets the criteria under the same parent element.
The sample code is as follows:
p:last-of-type {
color: red;
}
The above code will select the last element among all <p>
elements under the same parent element and set its text color to red.
Use cases of the last selector
The last selector has many application scenarios in real-world projects. Below we will introduce some common use cases.
1. Last Paragraph
Suppose we have a document with many paragraphs, and we want to italicize the text in the last paragraph.
The HTML code is as follows:
<p>This is the first paragraph. </p>
<p>This is the second paragraph. </p>
<p>This is the last paragraph. </p>
The CSS code is as follows:
p:last-of-type {
font-style: italic;
}
In this example, the text of the last paragraph will be italicized. This will make the last paragraph stand out more clearly on the page.
2. Last List Item
Suppose we have an unordered list, and we want to set the background color of the last item to gray.
HTML code as follows:
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Last list item</li>
</ul>
CSS code as follows:
li:last-of-type {
background-color: lightgray;
}
In this example, the background color of the last list item will be set to gray. This will distinguish the last list item and make it stand out more clearly in the list.
3. Last Link
Suppose we have a navigation bar and we want to set the text color of the last link in the navigation bar to blue.
The HTML code is as follows:
<nav>
Home
Products
About Us
</nav>
The CSS code is as follows:
a:last-of-type {
color: blue;
}
In this example, the text color of the last link in the navigation bar will be set to blue. This will make the last link more prominent in the navigation bar.
Browser Compatibility
The last selector has excellent compatibility with modern browsers, including Chrome, Firefox, Safari, Edge, and other major browsers. However, older versions of Internet Explorer may not support this selector, so compatibility should be considered when using it.
Conclusion
The last selector is a very useful selector in CSS. It allows us to easily select the last element among elements that meet the criteria under the same parent element and apply styles to it. In real-world projects, the appropriate use of the last selector can make pages more beautiful and easy to read, while also improving development efficiency.