问题:
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
来源:oschina
链接:https://my.oschina.net/stackoom/blog/4319687