使用 LESS,我可以在嵌套的 child 元素中引用 parent 元素吗

Using LESS, can I reference a parent element in nested child elements

我有一个 table,有一个 header 行和许多数据行。我在第一列中有一个复选框。在 th 单元格中,我想在 td 单元格中添加顶部和底部边距,我不想要这个。

我有 LESS(css) 对于 thtd 元素与 class .col-checkbox 以及label 两个单元格中的元素共享 css。如果标签位于 th 单元格中,我想将边距 top/bottom 添加到标签中。

.html 文件

<table>
    <tr>
        <th class="col-checkbox">
            <div>Column Label</div>
            <label class="custom-checkbox">
                <input type="checkbox" />
                <span class="checkbox"></span>
            </label>
        </th>
        <th>
           Unimportant, there are more columns as well
        </th>
    </tr>
    <tr>
        <td class="col-checkbox">
            <label class="custom-checkbox">
                <input type="checkbox" />
                <span class="checkbox"></span>
            </label>
        </td>
        <td>
           Unimportant, there are more columns as well
        </td>
    </tr>
</table>

.less 文件

.col-checkbox {
    width: 30px;
    // more css here

    label.custom-checkbox {
         height: 24px;
         // more css here

        // I know I can do the following, but I'd like to not have to add
        // more classes if I can someone make this dependent on whether it 
        // is in the th or td element
        //&.header {
        //    margin: 6px auto;
        //}
        //
        //&.data {
        //    margin: 0 auto;
        //}
    }
}

我知道我可以按照上面的方式让它工作,但我很好奇我是否可以仅通过引用 tdth 元素而不复制其他 css。我不这么认为,但我想我还是要问一下。

看来您已经很熟悉 & 运算符了。好吧,它 没有 放在选择器之前。相反,您可以在选择器之后使用它,例如 th&,以获得您想要的。

所以这个:

.col-checkbox {
  width: 30px;
  // more css here

  label.custom-checkbox {
    height: 24px;
    // more css here
  }

  th& {
    margin: 10px 0;
  }
}

输出这个:

.col-checkbox {
  width: 30px;
}
.col-checkbox label.custom-checkbox {
  height: 24px;
}
th.col-checkbox {
  margin: 10px 0;
}

但是,请注意,如果嵌套不止一层,此模式可能无法按预期工作。

考虑这段代码:

.col-checkbox {
  width: 30px;
  // more css here

  label.custom-checkbox {
    height: 24px;
    // more css here
    .checkbox& {
      color: navy;
    }
  }
}

你可能希望从中得到这个:

.col-checkbox {
  width: 30px;
}
.col-checkbox label.custom-checkbox {
  height: 24px;
}
.col-checkbox label.custom-checkbox.checkbox {
  color: navy;
}

但实际上你会得到这个:

.col-checkbox {
  width: 30px;
}
.col-checkbox label.custom-checkbox {
  height: 24px;
}
.checkbox.col-checkbox label.custom-checkbox {
  color: navy;
}