I've got a problem with the css nth-child selector.
I have a grid of 3x3 elemtens inside a container. Those elements have a class called .square
.
With .square:nth-child(3n+1)
I select every first element of the row and color it green.
With .square:nth-child(3n+3)
I select every last element of the row and color it red.
This works fine, until there is any element(<br>
for example) that is outputted before the grid. With every new <br>
, the order moves up by one, as is the <br>
was considered a .square
.
As I understand the .nth-child
, it should select every third element of the .square
class. Why does it apply that to any element, and how can I achieve my inital goal?
Thanks in advance
http://www.hier-krieg-ich-alles.de/shop.php?cat=26491127728
The problem occurs on the boxes in the middle.
The :nth-child() CSS pseudo-class selector is used to match the elements based on their position in a group of siblings. It matches every element that is the nth-child, regardless of the type, of its parent.
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.
As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .
The :nth-child() is a CSS pseudo-class selector that allows you to select elements based on their index (source order) inside their container. You can pass in a positive number as an argument to :nth-child() , which will select the one element whose index inside its parent matches the argument of :nth-child() .
Sounds like you want nth-of-type
.
Related selectors which you may find useful are :first-of-type
, :last-of-type
, :nth-last-of-type
and :only-of-type
.
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