我有一堆带有类名的元素red,但我似乎无法class="red"使用以下CSS规则选择第一个元素:
.red:first-child {
border: 5px solid red;
}Run Code Online (Sandbox Code Playgroud)
<p class="red"></p>
<div class="red"></div>Run Code Online (Sandbox Code Playgroud)
这个选择器有什么问题,我该如何纠正?
感谢这些评论,我发现该元素必须是其父母的第一个孩子才能被选中,这与我的情况不同.我有以下结构,这条规则失败,如评论中所述:
.home .red:first-child {
border: 1px solid red;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
我怎样才能让第一个孩子上课red?
正如标题所说,我想将css规则添加到具有某个类的某个类型的最后一个元素.以下代码完美运行:
div:last-of-type { margin-right:0; }
Run Code Online (Sandbox Code Playgroud)
但我想要类似的东西
div.class:last-of-type { margin-right:0; }
Run Code Online (Sandbox Code Playgroud)
这该怎么做 ?
如何在元素列表中选择某个元素?我有以下内容:
<div class="myclass">my text1</div>
<!-- some other code follows -->
<div>
<p>stuff</p>
</div>
<div>
<p>more stuff</p>
</div>
<p>
<span>Hello World</span>
</p>
<div class="myclass">my text2</div>
<!-- some other code follows -->
<div>
<p>stuff</p>
</div>
<p>
<span>Hello World</span>
</p>
<input type=""/>
<div class="myclass">my text3</div>
<!-- some other code follows -->
<div>
<p>stuff</p>
</div>
<footer>The end</footer>
Run Code Online (Sandbox Code Playgroud)
我有一个div.myclass {doing things}适用于所有人的CSS类,很明显,但是我也希望能够.myclass像这样选择第一,第二或第三个div类,无论它们在标记中的位置如何:
div.myclass:first {color:#000;}
div.myclass:second {color:#FFF;}
div.myclass:third {color:#006;}
Run Code Online (Sandbox Code Playgroud)
几乎像jQuery索引选择.eq( index ),这是我目前使用的,但我需要一个无脚本替代.
具体来说,我正在寻找伪选择器,而不是添加另一个类或使用ID来使事情有效.
p:nth-child(2)和之间有什么区别p:nth-of-type(2)?
p:nth-child(2):选择<p>作为其父级的第二个子元素的每个元素.p:nth-of-type(2):选择作为其父元素<p>的第二个<p>元素的每个元素.所不同的似乎是其父母的孩子和<p> 其父母的元素.
如果我们已经<p>在两种情况下都提到了元素类型,并且关键字parent建立了父子关系,那么有什么区别呢?
也许这个问题很荒谬,但我想知道这个事实.我有一个li带有两个类的元素(见下文),但它没有像我预期的那样工作.有人知道原因吗?
.red:first-child {
color:#F00;
}
.blue:first-child {
color:#00F; /* not working */
}
.red:last-child {
color:#F00; /* not working */
}
.blue:last-child {
color:#00F;
}Run Code Online (Sandbox Code Playgroud)
<ul>
<li class="red">one</li> <!-- This is the first child of red -->
<li class="red">two</li>
<li class="red">three</li>
<li class="blue">one</li> <!-- and this first child of blue -->
<li class="blue">two</li>
<li class="blue">three</li>
</ul>Run Code Online (Sandbox Code Playgroud)