How to let DOM elements stack and overflow horizontally rather than vertically in HTML?

Do I need a container that is very wide and set the elements for inline display or float or something else? What if I have two lines, each of which occupies 50% of the height?

What to do if the number of elements is not defined? How to determine the width of the container?

It seems very difficult with a div. Do I need to use a table?

Also, it is very difficult in pure css, as it is confusing and difficult to control relative width and height at the same time. Should I use JS?

What is the easiest and most elegant way to do this?

+5
source share
2 answers

It sounds very much like you want to use the CSS attribute: Flexbox

With a flexible frame, you can define the maximum and minimum width and height, and the maximum / maximum number of elements before they hit a new line.

The beauty is that you let the browser calculate the width, you just define max, min, margin and padding.

And its all CSS, no javascript required

Take a look at the examples in css tricks and play with it. This link is relatively old, so some of the vendor prefixes are no longer needed.

Hope this helps!

EDIT: More info on flex attribute can be found in Mozilla

+1
source

The easiest way is to use Freemasonry ( http://masonry.desandro.com/ )

You can align your divs horizontally, but you will run into problems if they do not have a given height, as they will begin to stagger like steps when they extend to the second / third row, etc ...

0
source

All Articles