# div 標籤和 後代選擇器 - 為什麼需要後代選擇器? 範例解釋: 1. 重複撰寫多個 `class `很麻煩: 於`a`標籤上撰寫兩個區塊,分別是紅色與藍色 但這樣至少就要寫6次 `class` 2. style1 - red , style-2 - blue ![](https://i.imgur.com/Cf0LEGH.png) ``` <a href="#" class="style1">red</a> <a href="#" class="style1">red</a> <a href="#" class="style1">red</a> <!-- --> <a href="#" class="blue">blue</a> <a href="#" class="blue">blue</a> <a href="#" class="blue">blue</a> // css .style1 { color: red; } .style2 { color: blue; } ``` - 使用 `div` 標籤來區分: - 此時會發現: `.style2` 因為 div **區塊元素的特性**,被推擠下去: ![](https://i.imgur.com/dYeLC4m.png) ``` <div> <a href="#" class="style1">red</a> <a href="#" class="style1">red</a> <a href="#" class="style1">red</a> </div> <div> <a href="#" class="style2">blue</a> <a href="#" class="style2">blue</a> <a href="#" class="style2">blue</a> </div> ``` --- ### 後代選擇器的寫法: ``` <div class="style1"> <a href="#">red</a> <a href="#">red</a> <a href="#">red</a> </div> <div class="style2"> <a href="#">blue</a> <a href="#">blue</a> <a href="#">blue</a> </div> // 指定到 .style1 裡面的 a 標籤 .style1 a { color: red; } // 指定到 .style2 裡面的 a 標籤 .style2 a { color: blue; } ``` ###### tags: `HTML、CSS`