CSS nth of type
Created By: chatGPT
The
:nth-of-type()
pseudo-class in CSS is used to select elements based on their position relative to their parent element. This can be particularly useful when you want to style specific items within a group without adding additional classes or IDs. It takes an expression that allows you to match elements based on their order, such as odd, even, or every third item./* Example of using :nth-of-type() */
ul {
list-style-type: none;
padding: 0;
}
li {
background-color: lightgray;
margin: 5px 0;
padding: 10px;
}
li:nth-of-type(odd) {
background-color: #f0f0f0;
}
li:nth-of-type(3n) {
background-color: lightblue;
}
In the code example above, all odd list items (
li:nth-of-type(odd)
) will have a light gray background, while every third item (li:nth-of-type(3n)
) will have a light blue background. This allows for an effective way to create striped effects or highlight certain items in a list./* HTML Structure */
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
:nth-of-type()
can be combined with other pseudo-classes for more granular control. You can even use mathematical expressions to define the selection criteria. For instance, :nth-of-type(2n+1)
will select all odd items, and :nth-of-type(4n)
will select every fourth item starting from the fourth.li:nth-of-type(2n+1) {
color: red;
}
li:nth-of-type(4n) {
font-weight: bold;
}