类的第一个元素的CSS选择器

蹲街弑〆低调 提交于 2020-07-25 17:48:32

问题:

I have a bunch of elements with a class name red , but I can't seem to select the first element with the class="red" using the following CSS rule: 我有一堆元素的类名是red ,但是我似乎无法使用以下CSS规则选择class="red"的第一个元素:

.red:first-child { border: 5px solid red; }
<p class="red"></p> <div class="red"></div>

What is wrong in this selector and how do I correct it? 该选择器有什么问题,我该如何纠正?

Thanks to the comments, I figured out that the element has to be the first child of its parent to get selected which is not the case that I have. 多亏了这些评论,我才知道该元素必须是其父元素的第一个子元素才能被选中,而事实并非如此。 I have the following structure, and this rule fails as mentioned in the comments: 我具有以下结构,并且该规则失败,如注释中所述:

.home .red:first-child { border: 1px solid red; }
<div class="home"> <span>blah</span> <p class="red">first</p> <p class="red">second</p> <p class="red">third</p> <p class="red">fourth</p> </div>

How can I target the first child with class red ? 我该如何针对red班级的第一个孩子?


解决方案:

参考一: https://stackoom.com/question/BOwK/类的第一个元素的CSS选择器
参考二: https://oldbug.net/q/BOwK/CSS-selector-for-first-element-with-class
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!