繁体   English   中英

如何使用第一个孩子?

[英]How to use first-child?

我想选择名为“ aProduct”的第一个div,但是我对如何执行此操作有些困惑。 我已经尝试过了:

<div id="kasticketProducts">
    <div class="aProductHeader"></div>
    <div class="aProduct"></div>
    <div class="aProductHeader"></div>
    <div class="aProduct"></div>    
</div>

这是我当前的CSS:

#kasticketProducts:first-child .aProduct {
    margin-top: 30px;
    background: red;
}

#kasticketProducts:first-child .aProduct使用上面的css表示,它将首先在该第一个孩子中搜索带有kasticketproducts的ID,这里第一个孩子从此处尝试引用aProductHeader,但您尝试搜索的是aProduct,但不存在。 实际上,从DOM层次结构来看,aProduct类div是第二个子元素,在这里将其称为css中的nth-child(2),而无需再次使用.aProduct。因此,最终的解决方案是写为#kasticketProducts div:nth-child(2)

首先,有什么区别?

MDN

:first-child()

:first-child CSS伪类表示任何作为其父级的第一个子元素的元素。


:first-of-type()

:first-of-type CSS伪类表示其父元素的子代列表中其类型的第一个同级。

简而言之,与:first-of-type()相比, :first-child()有点松散的伪选择器


不幸的是:first-child:first-of-type不尊重id ,它们仅与DOM元素有关。 因此,如果您执行类似操作,将会失败

 #kasticketproducts div.aProduct:first-of-type { color: red; } 

因此,在这种情况下,最好的CSS处理方法是使用:nth-of-type() ,将2用作值,现在很明显,如果您的元素没有aProduct class ,它将失败

#kasticketproducts div:nth-of-type(2) {
    color: red;
}

演示

要么

您可以将相邻选择器与:first-of-type()

#kasticketproducts div:first-of-type + div {
    color: red;
}

演示

就IE而言,第二个解决方案更兼容

DEMO

代码不起作用,因为aProductHeader类在第一次出现aProduct类之前。

参见演示。

您可以使用

:first-child:nth-of-type(1) nth-child(1n) :first-of-type或: nth-child(1n)

为什么您的代码不起作用,是因为您使用:

#kasticketProducts:first-child .aProduct

这将采用第一个元素#kasticketProducts ,而应使用以下元素: #kasticketProducts .aProduct:nth-child(2) { color: red; } #kasticketProducts .aProduct:nth-child(2) { color: red; } <-这将在ID元素内使用第一个元素.aProduct

您无法定位类的第一个元素,但是你可以定位来后的元素,这样你就可以在所有设置的样式aProduct元素,然后将其覆盖在所有aProduct使用后的第一个自带~ opreator :

#kasticketproducts .aProduct {
    margin-top: 30px;
    background: red;
}
#kasticketproducts .aProduct ~ .aProduct {
    margin-top: 0;
    background: none;
}

演示: http//jsfiddle.net/a9W5T/

另一个解决方案是设置.aProduct样式,然后使用通用的同级组合器覆盖任何随后出现的.aProduct的样式:

#kasticketProducts .aProduct {
    // effectively becomes the style for the first occurrence of .aProduct
}

#kasticketProducts .aProduct ~ .aProduct {
    // overrides the style set above for all occurrences of .aProduct,
    // apart from the first
}

这种方法的最大优点是它不依赖标记的结构。

MDN上的通用同级选择器

这是一个例子

检查#id,区分大小写

另外,请小心引号,不要关闭引号。

<div id="kasticketProducts">
<div class="aProductHeader">aaa</div>
<div class="aProduct">aaa</div>
<div class="aProductHeader">aaaa</div>
<div class="aProduct">aaa</div> 

对于第一个.aProduct选择:

#kasticketProducts .aProduct:nth-child(2) {
    /* your styles */
}

抱歉,想到的是获得第一个kasticketProduct。 道歉。

暂无
暂无

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

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