Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify sibling selector in Less in short way?

Tags:

css

less

I have the following less rule:

.menu-link {
     & + .menu-link {
        border-left: 1px solid #000;
     }
}

It work fine but looks ugly because if my menu-link class get changed than I need to replace it two places.

Is there way to simplifying the rule above?

like image 331
Erik Avatar asked Feb 08 '15 20:02

Erik


People also ask

How do I select a specific sibling in CSS?

Adjacent Sibling Selector (+) The adjacent sibling selector is used to select an element that is directly after another specific element. Sibling elements must have the same parent element, and "adjacent" means "immediately following".

How do I select a previous sibling in SCSS?

No, there is no "previous sibling" selector. On a related note, ~ is for general successor sibling (meaning the element comes after this one, but not necessarily immediately after) and is a CSS3 selector. + is for next sibling and is CSS2.

How do I select a second sibling in CSS?

You use the general sibling selector (~) in combination with :hover . The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.


1 Answers

LESS - Parent Selectors

The & operator represents the parent selectors of a nested rule and is most commonly used when applying a modifying class or pseudo-class to an existing selector.

Since & represents the parent, you could simply use & + &:

.menu-link {
     & + & {
        border-left: 1px solid #000;
     }
}

..which compiles to:

.menu-link + .menu-link {
  border-left: 1px solid #000;
}

As a side note, & refers to the entire parent selector. Thus, if you were to use the following:

.parent {
  .menu-link {
    & + & {
      border-left: 1px solid #000;
    }
  }
}

..it would compile to the undesired result of:

.parent .menu-link + .parent .menu-link {
  border-left: 1px solid #000;
}

Therefore you would need to keep your selectors simple and use

.menu-link {
     & + & {
        border-left: 1px solid #000;
     }
}
like image 103
Josh Crozier Avatar answered Nov 15 '22 19:11

Josh Crozier