Immediate Child selector in LESS

前端 未结 5 1024
天涯浪人
天涯浪人 2020-12-05 03:48

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 {
    .         


        
相关标签:
5条回答
  • 2020-12-05 04:05

    The official way:

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

    & always refers to the current selector.

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

    0 讨论(0)
  • 2020-12-05 04:06

    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.

    0 讨论(0)
  • 2020-12-05 04:13

    In case that you need to target more selectors:

    .parent {
        >.first-child,
        >.second-child,
        >.third-child {
        ...
        }
    }
    
    0 讨论(0)
  • 2020-12-05 04:16

    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.

    0 讨论(0)
  • 2020-12-05 04:25

    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.

    0 讨论(0)
提交回复
热议问题