css - 如何从相同的嵌套 div 中选择特定的 HTML 元素

标签 css html

我需要选择一个特定的 HTML 元素,它们是相同的,也包含在几个相同的 div 中,我尝试使用 nth-child() 但它没有不行。 (每个 child 共享相同的属性,但有细微的变化)

HTML

<div class="disc">
  <div class="disc_PF">
  </div>
</div>
<div class="disc">
  <div class="disc_PF">
  </div>
  <div class="disc_PF">
  </div>
</div>

CSS

.disc .disc_PF:nth-child(1) {}

当我使用它时,它会选择第一个 disc_PF 元素,

CSS

.disc .disc_PF:nth-child(2) {}

当我使用它时,它会选择第三个 disc_PF 元素,

如何单独选择单个嵌套元素?

谢谢

最佳答案

这是您可以做到的。

.disc_PF
{
  width: 50px;
  height: 50px;
}

/* First .disc, all .disc_PF */
.disc:nth-of-type(1) > .disc_PF
{
  background: red;
}
/* Second .disc, first .disc_PF */
.disc:nth-of-type(2) > .disc_PF:first-child
{
  background: green;
}
/* Second .disc, .disc_PF that is the second child element */
.disc:nth-of-type(2) > .disc_PF:nth-child(2)
{
  background: yellow;
}
/* Second .disc, last .disc_PF */
.disc:nth-of-type(2) > .disc_PF:last-child
{
  background: blue;
}
<div class="disc">
  <div class="disc_PF">
  </div>
</div>
<div class="disc">
  <div class="disc_PF">
  </div>
  <div class="disc_PF">
  </div>
  <div class="disc_PF">
  </div>
</div>

关于css - 如何从相同的嵌套 div 中选择特定的 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42310847/

相关文章:

html - CSS 底部边框悬停 "jitter"

html - 无法在 IE 中使用深色背景?

c# - 将 div 的内容居中 - 使用 CSS

javascript - 表格上的 html 输入按钮不调用任何 jquery 函数

html - 如何隐藏 HTML 元素中第 n 个分隔符之后的所有内容?

javascript - 如何转换网页的一部分并即时创建样式和格式的 PDF?

javascript - 2 在不同的选项卡中相互重叠的文本 JQuery-UI

css - 子选择器不适用于过渡

jquery - 表单提交后复选框样式不起作用

html - 如何使用 CSS 和 <div> 让文本出现在 <td> 的底部?