CSS sets the style for the second element in each row
CSS Styles for the Second Element in Each Row
In web development, you often encounter situations where you need to set styles for specific elements. A common requirement is to set specific styles for the second element in each row. In CSS, we can use pseudo-class selectors to achieve this effect. This article will detail how to use CSS to style the second element in each row.
HTML Structure
First, let’s look at a simple HTML structure as an example. Suppose we have a list of products with three items per row, and we want to set specific styles for the second item in each row.
<div class="product-list">
<div class="product">Product 1</div>
<div class="product">Product 2</div>
<div class="product">Product 3</div>
<div class="product">Product 4</div>
<div class="product">Product 5</div>
<div class="product">Product 6</div>
</div>
Using Pseudo-Class Selectors
To style the second element in each row, we can use the CSS pseudo-class selector nth-child
. Specifically, we can use nth-child(3n+2)
to select the second element in each row. The following CSS code example sets the background color of the second element in each row to gray:
.product {
display: inline-block;
width: 100px;
height: 100px;
margin: 10px;
background-color: #f0f0f0;
}
.product:nth-child(3n+2) {
background-color: #ccc;
}
The above code sets the background color of the .product
element to light gray, and uses the nth-child(3n+2)
selector for the second product element in each row, setting its background color to dark gray.
Runtime Results
Next, let’s see the results of applying these styles. Assuming we include the above CSS styles in our HTML, when the page loads, the second product element in each row will have a specific background color.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set styles for the second element in each row</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="product-list">
<div class="product">Product 1</div>
<div class="product">Product 2</div>
<div class="product">Product 3</div>
<div class="product">Product 4</div>
<div class="product">Product 5</div>
<div class="product">Product 6</div>
</div>
</body>
</html>
In the above example, we successfully used the nth-child(3n+2)
selector to set specific styles for the second product element in each row, achieving our goal.
Summary
Through this article, we learned how to use the CSS pseudo-class selector nth-child
to set specific styles for the second element in each row. This method is very convenient and practical for similar situations, allowing us to concisely achieve the desired style.