【问题标题】:Create mixin with nth-child使用 nth-child 创建 mixin
【发布时间】:2014-06-12 01:35:18
【问题描述】:

我想在 LESS、CSS 中创建一个函数。 该函数应该在此执行:

.col{
    .run-the-function();
    }

问题是:例如,我希望该函数影响每三个孩子。

.test(@columns, @top-margin, @right-margin){
&:nth-child(@columns * n + 0 ){

}
}

总结: 当函数被执行时,每隔第三、第二、第四个元素或任何你设置的元素,该元素都会有一个红色边框。

你有什么想法吗?这甚至可能吗?

谢谢

【问题讨论】:

    标签: css less css-selectors


    【解决方案1】:

    我认为这可行

    .test(@columns, @top-margin, @right-margin){
        &:nth-child(@{columns}n){
    
        }
    }
    

    关于第n个孩子的更多信息https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

    【讨论】:

    • 嗯...为什么要使用@columns 两次,用(@columns * n) 还不够吗?我不认为它像 asterix:* 因为我的程序将它标记为红色,就像它在 asterix 上的错误一样我得到: ParseError: Unrecognized input in 所以我认为 * 在那里不起作用:/
    • 这是时代标志,LESS 可能会为此使用其他东西,或者将其包装在数学或其他东西中。如果你只做 columns * n 那么它将返回 0,当 n 从 0 开始时。
    • @user256631 我已编辑答案以更正乘法部分
    【解决方案2】:

    这行得通...

    输出是基于各种“第 n 个”值的交替行。 我很快就会在这里发布一张图片。

    标记:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Test</title>
        <link rel="stylesheet" href="/Content/test.css" />
    </head>
    <body>
       <div class="alt-rows every-3rd">
          <div>Test 1</div>
          <div>Test 2</div>
          <div>Test 3</div>
          <div>Test 4</div>
          <div>Test 5</div>
          <div>Test 6</div>
       </div>
       <br/>
       <div class="alt-rows every-2nd">
          <div>Test 1</div>
          <div>Test 2</div>
          <div>Test 3</div>
          <div>Test 4</div>
          <div>Test 5</div>
          <div>Test 6</div>
       </div>
    </body>
    </html>
    

    减:

    @bg: white;
    @alt-bg: gray;
    
    .altRows(@nth-row) {
       background-color: @bg;
       div:nth-child(@{nth-row}n+1) {
          background-color: @alt-bg;
       }
    }   
    
    .alt-rows {
       &.every-2nd {
          .altRows(2);
       }
    
       &.every-3rd {
          .altRows(3);
       }
    }
    

    【讨论】:

    • 我还能够通过使用循环使 Less 完全干燥。这摆脱了硬编码的“every-2nd”和“every-3rd”类。
    猜你喜欢
    • 2016-12-17
    • 2012-08-21
    • 1970-01-01
    • 2017-06-11
    • 2015-07-03
    • 1970-01-01
    • 2018-07-30
    • 2013-04-04
    • 2012-03-07
    相关资源
    最近更新 更多