📅  最后修改于: 2023-12-03 15:14:18.616000             🧑  作者: Mango
In CSS, the :not()
and :last-of-type
selectors are powerful tools that can be used to target specific elements in a document. The :not()
selector allows you to select elements that do not match a specified selector, while :last-of-type
allows you to select the last element of a specific type within a parent element. By combining these selectors, you can create more advanced and specific styling rules for your web page.
In this guide, we will explore how to use the :not()
and :last-of-type
selectors together to target specific elements and apply CSS styles to them.
The :not()
selector is used to select elements that do not match the specified selector. It takes the form :not(selector)
, where selector
can be any valid CSS selector. For example, :not(.class)
will select all elements that do not have the specified class.
The :last-of-type
selector is used to select the last element of a specific type within a parent element. It takes the form :last-of-type(selector)
, where selector
can be any valid CSS selector. For example, :last-of-type(p)
will select the last paragraph element within its parent.
To combine both selectors, you can use the :not(:last-of-type)
selector. This will select all elements that are not the last element of their type within their parent element. For example, div:not(:last-of-type)
will select all div
elements that are not the last div
within their parent.
Consider the following HTML markup:
<div class="container">
<p>Hello</p>
<p>World</p>
<p>Foo</p>
<p class="special">Bar</p>
<p>Baz</p>
</div>
We can use the CSS :not(:last-of-type)
selector to target all paragraphs except the last one within the .container
div:
.container p:not(:last-of-type) {
color: blue;
}
This will apply a blue color to all paragraphs except the last one.
The :not()
and :last-of-type
selectors in CSS provide powerful ways to target specific elements within a document. By combining them, you can create more advanced styling rules and apply styles to elements based on their position or other characteristics. Experiment with these selectors to enhance your web page design and improve its usability.