html - block 中具有特定类的第一个和最后一个元素的 CSS 选择器

标签 html css

我正在尝试为 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/

相关文章:

jquery - 添加/删除事件类 Onclick

javascript - 如何根据用户从 - 选择下拉菜单中所做的选择启用/禁用和更改某些链接的颜色 -

javascript - 将鼠标悬停在文本上以显示图像

Javascript 拒绝工作

html - 使用日期输入删除 vuetify v-text 字段上的向下箭头

javascript - $(element).width() 与其实际像素宽度之间的奇怪差异

html - SASS:有没有办法根据类名中的数字计算属性?

javascript - 插入 HTML 或附加 Child onClick,并从上一个单击的元素中删除

css - 什么是媒体查询的最佳宽度范围

Javascript 文件与 PHP 文件中的滚动条混淆