CSS Advanced Selectors Code
Overview
Sources:
TIP
There are many special selectors in CSS that allow us to query for a list of elements using advanced methods.
Code Snippets
Child Selectors
Child selectors allow us to select a specific set of children of an element according to their internal ordering.
First Child and Last Child
To select the first and last child contained withing a parent element, use the :first-child
and :last-child
selectors:
then in the HTML:
To make sure that we select only <li>
elements within a <ul>
element, we can use a relational selector:
Nth Child and Nth Last Child
Similarly to first-child and last-child, we can select using a fixed offset from the start and end of the list of children of the parent container.
Take a look at the following example:
First of Type and Last of Type
The first-of-type selector is very similar to the first-child selector, only that it is less restrictive - it only looks at elements of its type as opposed to the first-child selector.
Notice how the first CSS rule for coloring the first <li>
child in blue does not do anything, since it will only be applied to the first child element which is also an <li>
element. This example also shows that the first-of-type selector is usually less useful than its counterpart first-of-type.
Nth of Type and Nth Last of Type
Similarly to the previous section, nth-of-type
and nth-of-last-type
also is less restrictive by counting elements similar to its type, but also allows selecting an element using a fixed offset from either the start or the end of the list.
Only Child and Only of Type
The :only-child
selector will only select an element if it does not have any siblings at all contained within its parent element. The :only-of-type
is similar, only that it will only consider elements from the same type as itself.
Let’s take a look at both in action:
Notice how in this example the only-child selector fails to color the <dl>
element in read because of the presence of the <li>
element as a sibling. However, for the only-of-type selector, having a <dl>
element as a sibling is not an issue, since there are no other <li>
elements contained within the same parent.
Hierarchy Selectors
Empty Selector
The :empty
selector applies only to elements that are empty and contain only whitespaces and/or HTML comments.
Example:
Todo
- Adjacent sibling selectors (
+
and~
) - Special Selectors
- The Universal Selector (
*
) - The
not
Selector
- The Universal Selector (
- Attribute Selectors
- Basic Attribute Selector
- Attribute Equals Value Selector (
=
) - Attribute Contains Value Selector (
~=
and*=
) - Attribute Starts With Selectors (
|=
and^=
) - Attribute Ends With Selector (
$=
)
See Also
Appendix
Note created on 2024-04-15 and last modified on 2024-04-15.
Backlinks
(c) No Clocks, LLC | 2024