如果您需要以除默認(rèn)值之外的其他方式組合嵌套規(guī)則的選擇器,則 Parent選擇器運(yùn)算符有許多用途。 另一個(gè)典型的使用& 是重復(fù)生成類名。
下面的例子演示了在LESS文件中重復(fù)生成類名:
<html> <head> <link rel="stylesheet" href="style.css" type="text/css" /> <title>Parent Selector</title> </head> <body> <h2>Welcome to W3Cschool</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>
接下來,創(chuàng)建文件 style.less
.select { &-first { background-color: #58D3F7; } &-second { background-color: #F5F6CE; } &-third { background-color: #F5A9E1; } }
您可以使用以下命令將 style.less 文件編譯為 style.css :
lessc style.less style.css
接下來執(zhí)行上面的命令,它將用下面的代碼自動(dòng)創(chuàng)建 style.css 文件:
.select-first { background-color: #58D3F7; } .select-second { background-color: #F5F6CE; } .select-third { background-color: #F5A9E1; }
讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
將上述html代碼保存在 parent_selector22.htm 文件中。
在瀏覽器中打開此HTML文件,將顯示如下輸出。
更多建議: