简体   繁体   English

如何定位 css 中的子元素

[英]how to target an element child in css

Hello everyone in my case I want to target the 3 element for example, and I have the tags different, the 3 element can be p or div or something else, so I want to just target the 3 element what ever it is, i want to select always the 3 element.大家好,在我的情况下,我想以 3 元素为目标,并且我有不同的标签,3 元素可以是pdiv或其他东西,所以我只想以 3 元素为目标,无论它是什么,我想要到 select 始终是 3 元素。

Can I do that with CSS, if any help?如果有帮助,我可以用 CSS 做到这一点吗?

For example:例如:

<div>
  <p></p>
  <span><span>
  <div></div> //3 element here is div
  <a></a>
</div>

Or:或者:

<div>
  <div></div>
  <span><span>
  <p></p> //3 element here is p
  <a></a>
</div>
  1. If you would always have 4 tags, and want to target first 3,如果您总是有 4 个标签,并且想要定位前 3 个标签,

 div > *:not(:last-child){ background-color: red; }
 <div> <p>AAAAAAAAAAAAAAA</p> <span>AAAAAAAAAAAAAAA</span> <div>AAAAAAAAAAAAAAA</div> <a>AAAAAAAAAAAAAAA</a> </div>

  1. You could also target first 3 elements like below,您还可以定位前 3 个元素,如下所示,

 div > *:nth-child(-n+3){ background-color: red; }
 <div> <p>AAAAAAAAAAAAAAA</p> <span>AAAAAAAAAAAAAAA</span> <div>AAAAAAAAAAAAAAA</div> <a>AAAAAAAAAAAAAAA</a> </div>

if you only want to select first three child of a parent div(or any other element), you can do something like this,如果您只想 select 父 div(或任何其他元素)的前三个孩子,您可以这样做,

.parent:nth-child(1),
.parent:nth-child(2),
.parent:nth-child(3){
   //Your styles
}

Above code would select 1st, 2nd and 3rd child of the parent div to which i gave a class of parent.上面的代码将 select 父 div 的第一个、第二个和第三个子级,我给了父级的 class。 Also, if you want to select all the child of that parent div you could simply do as,此外,如果您想 select 该父 div 的所有孩子,您可以简单地执行以下操作,

.parent > *{
  //Your styles
}

this code would select all the child of the.parent div此代码将 select 所有子级的.parent div

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM