Use Nth:child to flip a div each time?

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

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?

1 Like

Yes this is exactly how i want it, thank you

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

Have you tried clearing the floats?

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

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.

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.

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:


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.