如何从相同的嵌套 div 中选择特定的 HTML 元素 [英] How to select a specific HTML element from identical nested divs

查看:30
本文介绍了如何从相同的嵌套 div 中选择特定的 HTML 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

HTML

<div class="disc_PF">

<div class="光盘"><div class="disc_PF">

<div class="disc_PF">

CSS

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

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

CSS

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

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

如何分别选择单个嵌套元素?

谢谢

解决方案

这是您的方法.

.disc_PF{宽度:50px;高度:50px;}/* 第一个 .disc,所有 .disc_PF */.disc:nth-of-type(1) >.disc_PF{背景:红色;}/* 第二个.disc,第一个.disc_PF */.disc:nth-of-type(2) >.disc_PF:第一个孩子{背景:绿色;}/* 第二个 .disc, .disc_PF 是第二个子元素 */.disc:nth-of-type(2) >.disc_PF:nth-child(2){背景:黄色;}/* 第二个.disc,最后一个.disc_PF */.disc:nth-of-type(2) >.disc_PF:最后一个孩子{背景:蓝色;}

<div class="disc_PF">

<div class="光盘"><div class="disc_PF">

<div class="disc_PF">

<div class="disc_PF">

I need to select a specific HTML element, which are identical, also contain inside several identical div's, I tried with nth-child() but it did not work. (Each child shares same properties with minor changes)

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) {}

When I use this, it selects both first disc_PF elements,

CSS

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

When I use this, it select third disc_PF element,

How can I select individual nested element separately?

Thanks

解决方案

Here's how you could do it.

.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>

这篇关于如何从相同的嵌套 div 中选择特定的 HTML 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆