LESS - 多重 &



描述

& 不僅代表最近的選擇器,還代表所有父選擇器。

示例

以下示例演示了在 LESS 檔案中使用 & 代表所有父選擇器的方法:

parent_selector.htm

<html>
   <head>
      <link rel = "stylesheet" href = "multiple1.css" type = "text/css" />
   </head>

   <body>
      <div class = "grand_parent">
         <h3>Welcome to TutorialsPoint</h3>
         <p class = "parent"> It is possible to reference the 
         parent selector by using &(ampersand) operator.</p>
         <p class = "parent_class">It is possible to reference the 
         parent selector by using &(ampersand) operator.</p>
      </div>
   </body>
</html>

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

style.less

.grand_parent {
   .parent {
      & > & {
         color: #A9F5F2;
      }

      & & {
         color: #D0FA58;
      }

      && {
         color: #81BEF7;
      }

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

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

lessc style.less style.css

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

style.css

.grand_parent .parent > .grand_parent .parent {
   color: #A9F5F2;
}

.grand_parent .parent .grand_parent .parent {
   color: #D0FA58;
}

.grand_parent .parent.grand_parent .parent {
   color: #81BEF7;
}

.grand_parent .parent,
.grand_parent .parent_class {
   color: #A4A4A4;
}

輸出

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

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

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

Less Parent Selector
less_parent_selectors.htm
廣告

© . All rights reserved.