Use Nth:child to flip a div each time?


#1

Hi I have a section of my website which will repeat itself in its design but will flip from float right to float left and repeat this pattern for as long as it goes.

Can I use Nth:child to solve this issue? if so whats the best approch


#2

Depends on the setup, but doing something like

.element:nth-child(2n + 1) {
  float: left;
}
.element:nth-child(2n + 2) {
  float: right;
}

The first rule will select every other (2n) .element starting with the first (1) element.

The second rule will select every other (2n) .element starting with the second (2) element.

Do you see how this works?


#3

Yes this is exactly how i want it, thank you


#4

after using this though my next section appears above the nth:child section ?


#5

Have you tried clearing the floats?


#6

i have yes but then its making the div appear behind them


#7

You will need to post the full code to replicate your issue and also perhaps a screenshot of the problem so that we can see which exact problem you are concerned with.

It certainly sounds like a float clearing and containment issue. If you don’t understand what that entails then that is the likely problem.:slight_smile:

Floats are basically removed from the flow and are not contained by their parents unless you use a containing mechanism so that the parent recognises they are there. Clearing a float is not the same thing but can result in the same thing in certain circumstances.


#9

How about a mock-up image of the intende layout?
Floats may be one way to do it, but it comes with issues. There may be another way to get what you want.


#10

It’s worth mentioning for those that follow that CSS recognizes the values even and odd for Nth-child, if you dont want to get fancy with formulae :wink: