Immediate Child selector in LESS

CssCss SelectorsLess

Css Problem Overview


Is there anyway to have LESS apply the immediate child selector ( > ) in its output?

In my style.less, I want to write something like:

.panel {
    ...
    > .control {
        ...
    }
}

and have LESS generate something like:

.panel > .control { ... }

Css Solutions


Solution 1 - Css

UPDATE

Actually, the code in the original question works fine. You can just stick with the > child selector.


Found the answer.

.panel {
    ...
    >.control {
        ...
    }
}

Note the lack of space between ">" and ".", otherwise it won't work.

Solution 2 - Css

The official way:

.panel {
  & > .control {
    ...
  }
}

& always refers to the current selector.

See http://lesscss.org/features/#features-overview-feature-nested-rules

Solution 3 - Css

The correct syntax would be following while using '&' would be redundant here.

.panel{
   > .control{
   }
}

According to less guidelines, '&' is used to parameterize ancestors (but there is no such need here). In this less example, &:hover is essential over :hover otherwise it would result in syntactic error. However, there is no such syntactic requirement for using '&' here. Otherwise all nestings would require '&' as they are essentially referring to parent.

Solution 4 - Css

In case that you need to target more selectors:

.parent {
    >.first-child,
    >.second-child,
    >.third-child {
    ...
    }
}

Solution 5 - Css

Also, If you are targeting the first child element, such as the first <td> of a <tr>, you could use something like this:

tr {
    & > td:first-child {font-weight:bold;}
}

this helps reduce class declarations when they aren't needed.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaveView Question on Stackoverflow
Solution 1 - CssDaveView Answer on Stackoverflow
Solution 2 - CssRicardo TomasiView Answer on Stackoverflow
Solution 3 - CsssbhartiView Answer on Stackoverflow
Solution 4 - CssstojsinsView Answer on Stackoverflow
Solution 5 - Cssseth yountView Answer on Stackoverflow