我正在尝试为 block 元素中的第一个和最后一个元素设置特定类的样式。我希望设置样式的元素不是该 block 的直接后代:
<div id="list">
<div>
<p class="line">This is the first line. I want to style this.</p>
<p class="line">Do not want to style this line</p>
<p class="line">Do not want to style this line</p>
<p class="line">Do not want to style this line</p>
</div>
<div>
<p class="line">Do not want to style this line</p>
<p class="line">Do not want to style this line</p>
<p class="line">Do not want to style this line</p>
<p class="line">This is the last line. I want to style this too.</p>
</div>
</div>
<div>
<p class="line">Do not want to style this line</p>
<p class="line">Do not want to style this line</p>
<p class="line">Do not want to style this line</p>
</div>
所以在这种情况下,我试图在#list 中选择带有类“line”的第一行和最后一行。
这有可能吗?
编辑:
虽然下面的所有答案都有效,但我发现我过度简化了问题。我想要的显然不能用 CSS 完成,至少需要一些 javascript。简而言之:我有一个行数可变的表。其中一些行属于某个类别。这些行在表中的位置是可变的,实际上可以通过用户交互进行更改。但我需要在此类的第一行和最后一行中设置一列的样式。我可以添加一个代码示例,但由于给出的答案实际上解决了我原来的问题,我认为最好按原样保留这个问题(并且可能为“真正的”问题开始一个新问题)。
最佳答案
如果结构足够严格,您可以使用 :fist-child
和 :last-child
。
#list>div:first-child>.line:first-child,
#list>div:last-child>.line:last-child {
color: green;
}
<div id="list">
<div>
<p class="line">This is the first line. I want to style this.</p>
<p class="line">Do not want to style this line</p>
<p class="line">Do not want to style this line</p>
<p class="line">Do not want to style this line</p>
</div>
<div>
<p class="line">Do not want to style this line</p>
<p class="line">Do not want to style this line</p>
<p class="line">Do not want to style this line</p>
<p class="line">This is the last line. I want to style this too.</p>
</div>
</div>
<div>
<p class="line">Do not want to style this line</p>
<p class="line">Do not want to style this line</p>
<p class="line">Do not want to style this line</p>
</div>
关于html - block 中具有特定类的第一个和最后一个元素的 CSS 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50338039/