Please see the html below:
<html>
<head>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div class="container1">
<div class="box1">1a</div>
<div class="box1">1b</div>
<div class="box1">1c</div>
</div>
<div class="container2">
<div class="box2">2</div>
<div class="box3">3</div>
<div class="box4">4</div>
</div>
</body>
</html>
and the css below:
.box1 {
background-color:red;
height:100px;
width:100px;
margin-bottom:10px;
}
.box2, .box3, .box4 {
height: 100px;
width: 100px;
margin-bottom:10px;
}
It now looks like this as expected:
.box2, .box3, .box4 {
height: 100px;
width: 100px;
margin-bottom:10px;
}
I now want to style box2; box3 and box4 specifically using the pseudo class: nth-child so it looks like this:
I realise I can just add this to the css:
.box2 {
background-color: yellow;
}
.box3 {
background-color: green;
}
.box4 {
background-color: purple;
}
However, I am trying to learn more about pseudo classes and want to use nth-child. I have tried this, which appears to make all of container2 green:
.container2:nth-child(1) {
background-color: yellow;
}
.container2:nth-child(2) {
background-color: green;
}
.container2:nth-child(3) {
background-color: purple;
}
I have also had a look what effect this has (I realise it won’t work as there are two div containers):
div:nth-child(1) {
background-color: yellow;
}
div:nth-child(2) {
background-color: green;
}
div:nth-child(3) {
background-color: purple;
}
The result is all over the place. What am I doing wrong?
2
Answers
:nth-child()
is applied to child elements not a parent element.link
You can think of
element:nth-child(2)
as the element which is the 2nd child of its parent.To achieve what you wanted, I added
bx
class tobox1
,box2
, andbox3
elements and applied:nth-child()
pseudo-class.Please check below result.
You are nearly there.
element:nth-child()
selects an element that is a specific child which is the wrong selector. You simply need a space between the container and the child selector such as:.container2 :nth-child()
and it will work. You can make it shorter by using the Nested CSS module: