【问题标题】:Using LESS, can I reference a parent element in nested child elements使用 LESS,我可以在嵌套子元素中引用父元素吗
【发布时间】:2019-05-20 10:23:17
【问题描述】:

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

对于thtd 类的.col-checkbox 元素,以及两个共享css 的单元格中的label 元素,我的LESS(css) 是相同的。如果标签位于th 单元格中,我想将边距顶部/底部添加到标签中。

.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 单元格中,我想将边距顶部/底部添加到标签。"这是你想要的? th &gt; label (w3schools.com/csSref/sel_element_gt.asp) 所以你只选择了直接是 TH 子元素的 LABEL 元素。
  • 好的,你是说把它从我的嵌套格式中拉出来?我想我试图让它变得比本来应该的更难。谢谢
  • 一目了然,您正在寻找的是lesscss.org/features/…。 IE。 th&amp; {margin: 6px auto}.

标签: css less


【解决方案1】:

您似乎已经熟悉&amp; 运算符。好吧,它没有必须在选择器之前。相反,您可以在选择器之后使用它,例如th&amp;,以获得您想要的。

所以这个:

.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;
}

【讨论】:

  • 谢谢!这正是我一直在寻找的。我没有意识到我可以在选择器之后使用 &。
猜你喜欢
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 2013-11-01
  • 2023-03-08
  • 2011-10-22
  • 2020-11-20
相关资源
最近更新 更多