How to distribute floated elements evenly with a dynamic column and row count in CSS?

后端 未结 4 646
礼貌的吻别
礼貌的吻别 2020-12-05 11:26

I have multiple divs with a fixed width and height (think about some sort of catalog view with article pictures). Now I want to show them similar to the behavior of float:le

4条回答
  •  醉梦人生
    2020-12-05 11:57

    The closest pure CSS solution is based on text-align: justify.

    Here are two of my answers showing the technique:

    • Fluid width with equally spaced DIVs
    • How to set auto-margin boxes in flexible-width design using CSS?

    Here's a demo using your HTML/CSS: http://jsfiddle.net/thirtydot/5CJ5e/ (or fullscreen)

    There's a difference in the way your JavaScript and this CSS handles the last row if there's a different number of boxes compared to the other rows.

    Your JavaScript does this:

    My CSS does this:

    If what the CSS does with a different number of boxes on the last row is unacceptable, you could add some extra invisible boxes to complete the row:

    http://jsfiddle.net/thirtydot/5CJ5e/1/ (or fullscreen)

    Doing this has the issue that the invisible boxes increase the height of the containing element. If this is a problem, I can't think of a way to fix it without using a little JavaScript:

    http://jsfiddle.net/thirtydot/5CJ5e/2/ (or fullscreen)

    Of course, since JavaScript is now being used, you might as well use it to add the invisible boxes in the first place (instead of sullying the HTML):

    http://jsfiddle.net/thirtydot/5CJ5e/5/ (or fullscreen)

    (I also wrote a more complicated JavaScript fix for this in an earlier revision, before the idea of invisible boxes was brought to me. There should be no reason to use my old fix now.)

提交回复
热议问题