balanced alternating column layout in CSS3

前端 未结 6 1709
无人共我
无人共我 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 04:58

    EDIT: This is an interesting solution, but unfortunately it does not solve the problem that was asked for.

    The solution I propose here puts subsequent elements into alternating columns, so: 1 -> left, 2 -> right, 3 -> left, 4 -> right, etc.

    This is a interesting problem by itself, but not what was asked for.

    Thanks to @Nils in the comments for pointing this out.

    Original answer

    Here is my attempt with flex!
    https://jsfiddle.net/vqLr8t3e/

    I am not sure if it works in IE11.

    Code

    .the-beginning {
      background: green;
      color: white;
      font-weight: bold;
      text-align: center;
      cursor: pointer;
    }
    
    .the-end {
      background: red;
      color: white;
      font-weight: bold;
      text-align: center;
      cursor: pointer;
    }
    
    .container-outer {
      overflow: hidden;
    }
    
    .container {
      display: flex;
      flex-wrap: wrap;
      flex-direction: column;
      max-height: 19999px;
      margin-top: -10000px;
    }
    
    .container > div {
      width: 50%;
      box-sizing: border-box;
      border: 5px solid grey;
      padding: 5px;
      background: white;
      order: 1;
    }
    
    .container > div:nth-child(odd) {
      order: -1;
    }
    
    .container > div:nth-child(1),
    .container > div:nth-child(2) {
      margin-top: 10000px;
    }
    THE BEGINNING
    LEFT 0
    RIGHT 0
    RIGHT 0
    LEFT 1
    LEFT 1
    LEFT 1
    RIGHT 1
    LEFT 2
    RIGHT 2
    RIGHT 2
    RIGHT 2
    THE END

    Idea

    Use flex-direction: column; and flex-wrap: wrap; on the container, and width: 50%; on the items, as a first step towards showing the items in columns.

    Use order: -1; and order: 1 to sort odd and even elements into different columns.

    Use a gratuitous margin-top: 10000px; on the first element of each column, and a max-height: 19999px; on the container, so that no two such items fit into one column. This will make sure each of these items starts in a new column. Compensate with a negative margin-top on the container. Cut it off with an outer container with overflow: hidden;.

提交回复
热议问题