LESS - nth 表达式



描述

nth 表达式的形式在扩展中很重要,否则它会将选择器视为不同的。nth 表达式1n+2n+2是等价的,但扩展将此表达式视为不同的。

例如,创建一个包含以下代码的 LESS 文件:

:nth-child(n+2) {
   color: #BF70A5;
   font-style: italic;
}
.child:extend(:nth-child(1n+2)){}

当我们在命令提示符中编译上述代码时,您将收到如下所示的错误消息。

Less Extend

编译后,您将获得以下 CSS 代码。

:nth-child(n+2) {
   color: #BF70A5;
   font-style: italic;
}

在属性选择器中,引号类型并不重要,您可以在以下示例中看到:

示例

以下示例演示了在 LESS 文件中使用nth 表达式:

extend_syntax.htm

<!doctype html>
   <head>
      <link rel = "stylesheet" href = "style.css" type = "text/css" />
   </head>

   <body>
      <div class = "style">
         <h2>Hello!!!!!</h2>
      </div>
      <p class = "img">Welcome to TutorialsPoint</p>
   </body>
</html>

接下来,创建style.less文件。

style.less

[title = tutorialspoint] {
   font-style: italic;
}

[title = 'tutorialspoint'] {
   font-style: italic;
}

[title = "tutorialspoint"] {
   font-style: italic;
}
.style:extend([title = tutorialspoint]) {}
.container:extend([title = 'tutorialspoint']) {}
.img:extend([title = "tutorialspoint"]) {}

您可以使用以下命令将style.less文件编译为style.css

lessc style.less style.css

执行上述命令;它将自动创建包含以下代码的style.css文件:

style.css

[title = tutorialspoint],
.style,
.container,
.img {
   font-style: italic;
}

[title = 'tutorialspoint'],
.style,
.container,
.img {
   font-style: italic;
}

[title = "tutorialspoint"],
.style,
.container,
.img {
   font-style: italic;
}

输出

按照以下步骤查看上述代码的工作原理:

  • 将上述 html 代码保存在extend_syntax.htm文件中。

  • 在浏览器中打开此 HTML 文件,将显示以下输出。

Less Extend
less_extend.htm
广告

© . All rights reserved.