Working with floating elements in CSS.

Sachin Chopra
Jul 25, 2017 · 1 min read

One common problem that occurs when you first work with floating elements is that the height of parent collapses.

After someone in my team was recently stuck on the same problem recently, I decided to properly document a good solution for once and for all.

So, lets see why you would want to float an element :-

1/ For scrollable components.
Here there is horizontal list of products and your users can scroll the list horizontally to see more content.

2/ For auto slideshow like components.
Here the elements automatically scroll into view every x seconds.

Both cases are pretty similar, only difference is that in case 1/ , you want the div to be scrollable whereas in case 2/ it shouldn’t be scrollable (should scroll automatically by amount x , every t milliseconds).

So, to make any of these layouts:

1/ Have a div which has width equal to your component width(for eg. your viewport / display width) and set -
overflow = auto (for case 1)
overflow = hidden (for case 2).

2/ Now have a child div which has much larger width than the viewport/display width ( atleast n * w, where n = number of elements you want to float and w = width of each floated element).

This is the container which will actually scroll.

3/ Now inside this put your floated elements.

Check out this fiddle for working example.

Sachin Chopra

Written by

Excited about Web

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade