html5 first child,html - CSS - Select first child with class - Stack Overflow

I have recently been trying to get my head around why this is not working. Ive started pulling my hair out trying to find a nice solution to a simple problem but every way that I can find to do this just seems messy. Basically what I would like to do is apply some styling to the first child with a specific class within a parent, in my example I am trying to apply a background color of red to the first instance of .class within each .parent. You can see my attempts in the fiddle here.

Here is the final code that I created that is working. The problem is that this seems very messy and I really dont like the fact that I have to set all of the .child classes to red then set all but the first back to white. There must be a cleaner/better way to do this?

HTML

Paragraph

Child 1
Child 2
Child 3
Child 4

Paragraph

Broken
Child 1
Child 2
Child 3
Child 4

CSS

/*** Does Not Work ***/

.child:first-child{

background-color:#f00;

}

/*** Does Not Work ***/

.child:nth-of-type(1){

background-color:#f00;

}

/*** Works But Is Messy! ***/

.child{

background-color:#f00;

}

.child ~ .child{

background-color:#fff;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值