Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Trying to fill a gap of a floated element

I have 4 floated sections in two columns. I'm wondering how you would go about getting the 3rd floated section to move up and fill the gap under the first floated section. I know the gap is because the 2nd float has more text. So far, the only way I have worked around the problem is by setting the 2nd section (float 2) to float right but this seems to only work when there are two columns as things start to fall apart when moving to 3 or more columns.

I'm trying to avoid having to use absolute positioning to resolve this if possible or negative margins (which I did try and that had a strange effect and didn't come close to forcing the 3rd section to move up as expected.

There's probably a much more efficient workaround to this but I can't seem to figure it out.

Any help would be appreciated

https://w.trhou.se/d5q39r3pj9

Thanks

1 Answer

Steven Parker
Steven Parker
243,318 Points

Just alternate the float direction.

In this case, just float the even-numbered sections to the right.

main section:nth-child(even) {
  float: right;
}

And yes, this only works for 2 columns. If you want to create this effect with more than 2 columns, then floats are probably not the way to go.

What you're doing is called a "masonry layout", and there's plenty of support for it on the web, such as this example from W3Bits. You'll find plenty more with your search engine.

Thanks very much for the information. I had no idea there was a given name for what I was doing and a meaningful name at that. I've taken a look at the link your provided and that's exactly what I am aiming for. For now, I've noted the link to for further study once my knowledge improves. I'm still in the early stages of the 'Front End Development Track' and I'm just putting into practice everything I've learned so far before progressing onto new topics.