LESS - 多重 &



描述

透過使用&運算子,可以重複引用父選擇器而無需使用其名稱。在選擇器內,&可以多次使用。

示例

以下示例演示了在 LESS 檔案中使用多個 & 的方法:

<html>
   <head>
      <title>Parent Selector</title>
      <link rel = "stylesheet" href = "style.css" type = "text/css" />
   </head>

   <body>
      <h2>Welcome to TutorialsPoint</h2>
      <p class = "select">It is possible to reference the 
      parent selector by using &(ampersand) operator.</p>
      <p class = "select_class1">It is possible to reference the 
      parent selector by using &(ampersand) operator</p>
   </body>
</html>

接下來,建立 style.less 檔案。

style.less

.select {
   & + & {
      color: #A9F5F2;
   }

   & & {
      color: #D0FA58;
   }

   && {
      color: #81BEF7;
   }

   &, &_class1 {
      color: #A4A4A4;
   }
}

您可以使用以下命令將 style.less 檔案編譯為 style.css

lessc style.less style.css

執行上述命令;它將自動建立 style.css 檔案,其中包含以下程式碼:

style.css

.select + .select {
   color: #A9F5F2;
}

.select .select {
   color: #D0FA58;
}

.select.select {
   color: #81BEF7;
}

.select,
.select_class1 {
   color: #A4A4A4;
}

輸出

按照以下步驟檢視以上程式碼的工作原理:

  • 將上述 html 程式碼儲存在 parent_selector.htm 檔案中。

  • 在瀏覽器中開啟此 HTML 檔案,將顯示以下輸出。

Less Parent Selector

&不僅代表最近的選擇器,還代表所有父選擇器。有關更多資訊,點選此處

less_parent_selectors.htm
廣告

© . All rights reserved.