John Smith John Smith - 4 months ago 15
CSS Question

CSS psuedo classes, target first DIV .class within DIV

I thought I knew this. There's three DIVs (.service-box) inside one wrapper DIV (.p-div)

How do you target the first (or any..) of the three inner DIVs?

This works, shows the structure is correct, will remove all inner DIVs

div.p-div > div.service-box { display: none!important;}


I just can't target the first inner DIV.

I've tried
first-child
,
nth-of-type(1)
,
nth-child(1)


I did notice
nth-of-type(1n)
removes all inner DIVs like the first CSS line. While
nth-of-type(2n)
removes all but the 2nd inner DIV. Basically doing the opposite of what I would expect (apply display:none only to the 2nd DIV, leaving the others intact)

Gotta say I'm a little perplexed. Could just edit the HTML directly but..I thought we were past that you know?

Answer
.p-div > .service-box:first-of-type {
    background-color: red;
}

Get a child of .p-div that has class .service-box and then select only the first child.

.p-div could be anything: some-selector > .service-box:first-of-type

CodePen: http://codepen.io/theblindprophet/pen/JKpwLk

Comments