乐闻世界logo
搜索文章和话题

How to specify sibling selector in Less in short way?

1个答案

1

In Less, we can leverage nested rules to simplify and organize CSS code, making the specification of sibling selectors more intuitive and efficient. Sibling selectors have two main types: the adjacent sibling selector (using the + symbol) and the general sibling selector (using the ~ symbol). Below, I will demonstrate the usage of both.

Adjacent Sibling Selector (+)

The adjacent sibling selector + is used to select an element that immediately follows another element, sharing the same parent. In Less, you can use it as follows:

less
#parent { .child1 { color: blue; & + .child2 { color: red; } } }

In this example, .child1 and .child2 are sibling elements, with .child2 immediately following .child1. Here, the & symbol represents .child1 itself, and + .child2 specifies its adjacent sibling element .child2. Thus, the color is set to red only when .child2 immediately follows .child1.

General Sibling Selector (~)

The general sibling selector ~ selects all sibling elements that follow it, sharing the same parent. In Less, you can use it as follows:

less
#parent { .child1 { color: blue; & ~ .child3 { color: green; } } }

In this example, as long as .child3 is any sibling element following .child1, its color is set to green. This provides a powerful way to control the styling of all sibling elements following a specific element.

Through these examples, we can see that Less's nested rules and parent selector reference (&) significantly enhance CSS readability and maintainability, making the specification of sibling selectors quick and intuitive. This is particularly useful in complex style sheets, effectively reducing code duplication and improving development efficiency.

2024年7月20日 13:25 回复

你的答案