balanced alternating column layout in CSS3

前端 未结 6 1712
无人共我
无人共我 2021-02-08 04:32

I\'m trying create a balanced (2-) column-layout.

The content is not text but blocks and varies in height. The content should be placed alternatingly left and right, as

6条回答
  •  礼貌的吻别
    2021-02-08 05:02

    Updated: I believe this is almost impossible to achieve with CSS only. There are many different solutions, but they all require some compromises unless you are willing to use JavaScript or some server-side code.

    Using CSS columns

    Here's an alternate fiddle using reordered blocks. Here's a fiddle demo using CSS columns without reordering.

    You can use CSS colunms to change your block flow to vertical unless you alter the order of their output. If you can output odd numbers first, then even numbers, you win.

    1
    3
    2
    4
    .wrapper { column-count: 2; column-width: 100px; -moz-column-width: 100px; -webkit-column-width: 100px; width: 260px; } div { border: 1px solid #999; display: inline-block; margin: 10px; width: 100px; } .block1 { height: 100px; } .block2 { height: 130px; } .block3 { height: 150px; } .block4 { height: 100px; }

    This solution is not compatible with IE9 and below.

    Block Height Known

    If you do know your block heights you can solve this problem by using absolute positioning.

    block1 {
      height: 100px;
      position: absolute;
      left: 0; 
      top: 0;
    }
    
    block2 {
      height: 110px;
      position: absolute;
      left: 0; 
      top: 100px; /* The height of the div above it */
    }
    

    A big drawback is dynamic content; we seldom know block height. So this solution is very limited in its application unless you are willing to calculate the height block height.

    If you are willing to use JS

    Use a plugin like Masonry. Both in vanilla js or jQuery flavour.

    Other Options

    This leaves you with the following options that require some compromises.

    1. Group your blocks into columns. See this Fiddle for a demo. This will alter the flow of your blocks to vertical, then horizontal.

    2. Use display: inline-block; vertical-align: top; on your blocks. This will leave some white space below your blocks.

    3. Force the height of your blocks, rendering this a non-issue. For blocks with additional content use the overflow property to allow in-block scrolling.

    4. As others have commented, you could attempt to calculate the height of the blocks on the server.

提交回复
热议问题