Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css nth-child and classes

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.

like image 822
chabuya Avatar asked Feb 24 '12 09:02

chabuya


People also ask

Can we use Nth child with class in CSS?

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.

How do I select the nth child of a class in CSS?

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.

What is the difference between the nth child () and Nth-of-type () selectors?

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 .

What is the nth child in CSS?

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() .


1 Answers

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.

like image 56
Joe Avatar answered Sep 30 '22 12:09

Joe