LESS - 父選擇器



描述

父選擇器運算子有很多用途,例如,當您需要以與預設方式不同的方式組合巢狀規則的選擇器時。& 的另一個典型用途是重複生成類名。

示例

以下示例演示如何在 LESS 檔案中重複生成類名:

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

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

現在建立 style.less 檔案。

style.less

.select {
   &-first {
      background-color: #58D3F7;
   }
   &-second {
      background-color: #F5F6CE;
   }

   &-third {
      background-color: #F5A9E1;
   }
}

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

lessc style.less style.css

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

style.css

.select-first {
   background-color: #58D3F7;
}

.select-second {
   background-color: #F5F6CE;
}

.select-third {
   background-color: #F5A9E1;
}

輸出

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

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

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

Less Parent Selector
less_parent_selectors.htm
廣告
© . All rights reserved.