6 个强大的 CSS 选择器,真正帮助您编写干净的 CSS。

2025-05-24

6 个强大的 CSS 选择器,真正帮助您编写干净的 CSS。

最初发布在我的博客上



CSS 中的选择器用于选择元素并对其进行样式设置。它们的强大功能取决于我们使用哪种选择器。在本文中,我将带您了解 6 个强大的 CSS 选择器,它们将真正帮助您在下一个项目中编写简洁的 CSS 代码。

1. div >a

该选择器使我们能够选择a父元素为div标签的所有元素。

<!-- This one will be selected --> 
<div>
    <a></a>
</div>

<!-- This one will not be selected -->
<p>
    <a></a>
</p>
Enter fullscreen mode Exit fullscreen mode

2. div +a

此命令将选择紧跟元素后的所有a标签。如果标签和元素div之间有元素,则不会选择该元素。diva

<main>
<!-- This one will be selected -->
    <div></div>
    <a></a>
<!-- This one will be not selected -->
    <div></div>
    <p></p>
    <a></a>
</main>
Enter fullscreen mode Exit fullscreen mode

3. div ~a

此命令将选择所有位于同一层级元素a之前的标签div。换句话说,如果a标签之前没有元素div,但有div一个同级元素作为标签,则将选择该元素。

<main>
<!-- This one will be selected -->
    <div></div>
    <a></a>
<!-- This one will be selected -->
    <div></div>
    <p></p>
    <a></a>
    <section>
<!-- This one will be selected -->
    <div></div>
    <p></p>
    <a></a>
    </section>

    <footer>
<!-- This one will be not selected -->
    <p></p>
    <a></a>
    </footer>
</main>
Enter fullscreen mode Exit fullscreen mode

4.【属性^=值】

例如:[class^="list-"]
此选择器将选择包含属性的每个元素class,并且其值以list-

<main>
<!-- This one will be selected -->
    <div class="list-element"></div>
<!-- This one will be selected -->
    <div class="list-container"></div>
<!-- This one will be selected -->
    <div class="list-item"></div>
<!-- This one will be not selected -->
    <div class="list__footer"></div>
</main>
Enter fullscreen mode Exit fullscreen mode

5.[属性$=值]

例如:[src$=".png"]
这个将选择src其值以 结尾的每个属性.png

<div>
<!-- This one will be selected -->
    <img src="image1.png">
<!-- This one will be not selected -->
    <img src="image2.jpg">
<!-- This one will be selected -->
    <img src="image3.png">
<!-- This one will be not selected -->
    <img src="image4.svg">
</div>
Enter fullscreen mode Exit fullscreen mode

6.[属性*=值]

例如:[class*="-list"]
此选择器将选取所有class属性包含 的元素。位于类值的开头、中间还是结尾均-list无所谓。最重要的是,该值必须包含-list-list

<main>
<!-- This one will be selected -->
    <div class="main-list-container"></div>
<!-- This one will be selected -->
    <div class="primary-list"></div>
<!-- This one will be selected -->
    <div class="primary-list-item"></div>
<!-- This one will be not selected -->
    <div class="list-footer"></div>
</main>
Enter fullscreen mode Exit fullscreen mode

结论

有时,由于 CSS 文件可能很快就会变得过于冗长,很难找到需要样式的元素。根据你的使用场景,使用这种选择器可能会非常有用。

文章来源:https://dev.to/ibrahima92/6-powerful-css-selectors-that-will-really-help-you-write-clean-css-4bab
PREV
理解 React Redux 的 7 个步骤
NEXT
2020 年必须知道的 15 个 JavaScript 数组方法 1. some() 2. reduce() 3. every() 4. map() 5. flat() 6. filter() 7. forEach() 8. findIndex() 9. find() 10. sort() 11. concat() 12. fill() 13. includes() 14. reverse() 15. flatMap()