Home >Web Front-end >Front-end Q&A >How to achieve different styles for odd and even numbers in css
In CSS, you can use the ":nth-of-type()" selector with the keywords "even" and "odd" to select even-numbered rows and odd-numbered rows elements respectively, and add different styles; Syntax "Element:nth-of-type(odd){One style code}Element:nth-of-type(even){Another style code}". The keyword "even" is used to select every even child element, and the keyword "odd" is used to select every odd child element.
The operating environment of this tutorial: Windows 7 system, CSS3&&HTML5 version, Dell G3 computer.
In css, you can use the :nth-of-type() selector to select elements in even rows and odd rows respectively, and add different styles.
:nth-of-type(n) selector selects all elements that are the nth child element of a specific type of its parent element.
When used with the keywords even and odd, you can select even and odd rows
even selects each even sub-element.
odd Select every odd child element.
Example: Specify two different background colors for odd and even p elements
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> p:nth-of-type(odd) { background:#ff0000; } p:nth-of-type(even) { background:#0000ff; } </style> </head> <body> <h1>This is a heading</h1> <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> </body> </html>
You can also select even numbers by formula rows and odd-numbered rows, but this will be a bit troublesome:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> p:nth-of-type(2n) { background:#ff0000; } p:nth-of-type(2n+1) { background:#0000ff; } </style> </head> <body> <h1>This is a heading</h1> <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> </body> </html>
The formula 2n
means selecting even-numbered sub-elements, 2n 1
means Select odd-numbered subelements.
(Learning video sharing: Getting started with web front-end)
The above is the detailed content of How to achieve different styles for odd and even numbers in css. For more information, please follow other related articles on the PHP Chinese website!