Reputation: 10230
I have the following HTML:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>
And the following CSS applied to it:
body {
padding: 0;
margin: 0;
display: flex;
align-items:center;
justify-content:center;
height: 100vh;
background: #eee;
}
ul {
max-width: 400px;
min-width: 400px;
}
ul > li {
overflow: hidden;
float: left;
width: 30%;
height: 50px;
margin: 1%;
background: orange;
color: #fff;
display: flex;
align-items:center;
justify-content:center;
}
ul > li:nth-child(3n + 1):nth-last-child(3) {
background: #727272;
}
You can see the same in the fiddle HERE.
Now the following selector:
ul > li:nth-child(3n + 1):nth-last-child(3) {
background: #727272;
}
Seems to be selecting the first element in the last row, I am not quite understanding how ?
Also
ul > li:nth-child(3n + 1):last-child {
background: #727272;
}
Does't work. Why ?
I would infact expect the following selector to select the first element on the last row:
ul > li:nth-child(3n + 1):nth-last-child(1) {
background: #727272;
}
So what exactly am i misinterpreting here , Why does multiple nth-child
selection not work the way i expect it to ?
How i am trying to achieve: Select the first element in the last row .. i believe i have already acheived that , just don't know how it works.
Upvotes: 0
Views: 206
Reputation: 114990
This..
ul > li:nth-child(3n + 1):nth-last-child(1) {
background: #727272;
}
does not work because it doesn't meet both conditions.
It's not :nth-last-child(1)
AND :nth-child(3n+1)
so it isn't selected.
This works
ul > li:nth-child(3n + 1):nth-last-child(3) {
background: #727272;
}
becuasie it IS both li:nth-child(3n + 1)
AND :nth-last-child(3)
.
However, the fact that it selects the first element in the last row is purely coincidental.
CSS cannot detect layout. it has no idea that this is in a row at all. CSS selects elements and nothing else.
Upvotes: 2