CSS select multiple elements left and right
CSS Select Multiple Elements Left and Right
In CSS, we often need to select multiple elements to apply styles. Sometimes we may need to select multiple elements to the left or right of an element. This article details how to use CSS selectors to select multiple elements to the left or right of an element, along with some practical examples.
Selecting the Left Element
To select an element to the left of an element, use the pseudo-class selector :nth-child()
in conjunction with the -n
keyword. :nth-child(-n)
selects the first n
elements. Replacing -n
with n
selects the n
th element.
The sample code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Select Left Elements</title>
<style>
div:nth-child(-n+2) {
color: red;
}
</style>
</head>
<body>
<div>Element 1</div>
<div>Element 2</div>
<div>Element 3</div>
<div>Element 4</div>
</body>
</html>
In the above example, we select the first two elements and apply the color: red;
style. The results are as follows:
Element 1 - Red
Element 2 - Red
Element 3
Element 4
Select the element to the right
To select the element to the right of an element, you can also use the pseudo-class selector :nth-child()
combined with the n
keyword. :nth-child(n)
selects the n
th element. Replacing n
with -n
selects the n
th element from the beginning.
The sample code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Select Right Elements</title>
<style>
div:nth-child(n+3) {
background-color: yellow;
}
</style>
</head>
<body>
<div>Element 1</div>
<div>Element 2</div>
<div>Element 3</div>
<div>Element 4</div>
</body>
</html>
In the above example, we select the third and fourth elements and apply the background-color: yellow;
style. The result is as follows:
Element 1
Element 2
Element 3 - Yellow background
Element 4 - Yellow background
Actual Application Scenarios
In real-world projects, we may need to select multiple elements, such as highlighting adjacent links to the left and right of the current page in a navigation bar. Here is a sample code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Highlight Current Nav Link</title>
<style>
ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
}
li {
margin: 0 10px;
}
li:nth-child(2) {
color: red;
}
li:nth-child(2) + li,
li:nth-child(2) + li + li {
color: blue;
}
li:nth-child(2) ~ li {
color: green;
}
</style>
</head>
<body> <ul>
<li>Home</li>
<li>About</li>
<li>Services</li>
<li>Contact</li>
</ul>
</body>
</html>
In the above example, we use the selectors :nth-child(2) + li
and :nth-child(2) ~ li
to select the left and right elements of the currently selected element, and apply different color styles to them respectively.