I'm trying to select the 3rd element, and then every 4.
So it would select 3, 7, 11, 15, 19, 23... etc.
.project:nth-child(3), .project:nth-child(7n+4) {
margin: 40px 0px 0px 0px;
}
What is wrong with the current code? It's not working, the margin is still set to 40px on the right margin.
The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
How do I target every third element in CSS? formula (an + b) In addition to the value n being able to be any number, you can also use a formula. nth-child(3n) would affect every third child element. nth-child(3n+1) would apply to every third element starting from the first one.
Issue
Your first selector is selecting the third element:
.project:nth-child(3)
However, your second selector is selecting every 7th element starting at the 4th:
.project:nth-child(7n+4)
Solution
You can combine your selectors to eliminate redundancy and modify your second selector to:
nth-child(4n+3)
so that your final CSS reads:
.project:nth-child(4n+3) {
margin: 40px 0px 0px 0px;
}
This will select every fourth element (4n) starting at the third element and also select the third element itself (+ 3).
Example
Here is an example snippet:
p:nth-child(4n+3) {
background:red;
}
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>
<p>11</p>
<p>12</p>
<p>13</p>
<p>14</p>
<p>15</p>
<p>16</p>
<p>17</p>
<p>18</p>
<p>19</p>
<p>20</p>
<p>21</p>
<p>22</p>
<p>23</p>
<p>24</p>
<p>25</p>
<p>26</p>
<p>27</p>
<p>28</p>
<p>29</p>
<p>30</p>
<p>31</p>
<p>32</p>
<p>33</p>
<p>34</p>
<p>35</p>
<p>36</p>
<p>37</p>
<p>38</p>
<p>39</p>
<p>40</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With