Home  >  Article  >  Web Front-end  >  How to achieve different styles for odd and even numbers in css

How to achieve different styles for odd and even numbers in css

青灯夜游
青灯夜游Original
2022-08-29 18:05:272683browse

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.

How to achieve different styles for odd and even numbers in css

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>

How to achieve different styles for odd and even numbers in css

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>

How to achieve different styles for odd and even numbers in css

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn