How to use:nth-child(-n 5) pseudo-class selector to select the CSS style of child elements with position less than or equal to 5
In CSS, pseudo-class A selector is a powerful tool that can select certain elements in an HTML document through a specific selection method. Among them, :nth-child() is a commonly used pseudo-class selector that can select child elements at specific positions.
:nth-child(n) can match the nth child element in HTML, and :nth-child(-n) can match the penultimate nth child element in HTML. Combining the two, we can use :nth-child(-n 5) to select child elements with positions less than or equal to 5.
The specific code examples are as follows:
HTML code:
CSS code:
ul li:nth-child(-n+5) { color: red; }
In the above code, we selectedul
lisub-elements whose position is less than or equal to 5 in the
element, and set their text color to red.
Run the above code, you will find that the text color of list item 1 to list item 5 is set to red, while the text color of list item 6 to list item 10 remains default.
It should be noted that the:nth-child()
selector selects based on the position of the child element. If there are other types of sub-elements in theul
element, such asdiv
,span
, etc., they will not be affected and onlywill be selected. li
element. So when using this selector, you should pay attention to the hierarchical relationship of the HTML structure.
In addition to text color, the:nth-child(-n 5)
selector can also be used to set other styles, such as background color, font size, etc. Just replacecolor: red
with the corresponding style setting.
In short, by using the :nth-child(-n 5) pseudo-class selector, we can simply select child elements with positions less than or equal to 5 and apply specific CSS styles to them, thereby achieving more flexibility web design.
The above is the detailed content of How to use:nth-child(-n+5) pseudo-class selector to select the CSS style of child elements whose position is less than or equal to 5. For more information, please follow other related articles on the PHP Chinese website!