Apply style to child elements with LESS

2019-07-18 22:22发布

问题:

This works:

.layoutList {
    background-color: #CFCFCF;
}
.layoutList > .entityCard.hover {
    background-color: #FFFFFF;
    border: 1px solid yellow;
}

Why doesn't this work the same as the above code? What is the appropriate way to "cascade" this in LESS so that everything is under the main .layoutList {} section?

.layoutList {
    background-color: #CFCFCF;
    .entityCard.hover {
        background-color: #FFFFFF;
        border: 1px solid yellow;
    }
}

回答1:

What you have for your LESS should work. It compiles to this CSS:

.layoutList {
  background-color: #CFCFCF;
}
.layoutList .entityCard.hover {
  background-color: #FFFFFF;
  border: 1px solid yellow;
}

The only thing missing is if you want the child combinator as your example shows, then you need to tweak your LESS to this (where the > was added):

.layoutList {
    background-color: #CFCFCF;
    > .entityCard.hover {
        background-color: #FFFFFF;
        border: 1px solid yellow;
    }
}

Which will then output this:

.layoutList {
  background-color: #CFCFCF;
}
.layoutList > .entityCard.hover {
  background-color: #FFFFFF;
  border: 1px solid yellow;
}


标签: css less