DIV Vertically floating DIV arrange from up to down by rows

前端 未结 3 683
青春惊慌失措
青春惊慌失措 2021-01-21 22:38

I am trying to locate DIVs vertically from up to down inside container. Container should be limited vertically by 500px. All DIVs that couldn\'t fit in this limit should be floa

3条回答
  •  长发绾君心
    2021-01-21 22:57

    CSS columns seem like a promising solution at first, but they won't automatically adjust the width of the container as areas are added or removed.

    My suggestion is to lay out the divs as if you were stacking them horizontally rather than vertically, going from right to left. That is easy enough to achieve with float:right. Once you have that, you can rotate the whole container 90 degrees to get the equivalent vertical layout. But since the area divs will now all be incorrectly oriented, you'll also need to rotate those 90 degrees back in the opposite direction.

    Something like this:

    #container {
      position:relative;
      background-color:red;
      max-width:500px;
      margin-left:-500px;
      max-height:500px;
      overflow:hidden;
      -webkit-transform:rotate(-90deg);
      -webkit-transform-origin:top right;
      -ms-transform:rotate(-90deg);
      -ms-transform-origin:top right;
      transform:rotate(-90deg);
      transform-origin:top right;
      padding:20px 0 0 20px;
      -webkit-box-sizing:border-box;
      -moz-box-sizing:border-box;
      box-sizing:border-box;
    }
    #area {
      background-color:yellow;
      margin:0 20px 20px 0;
      width:100px;
      height:100px;
      float:right;
      -webkit-transform:rotate(90deg);
      -ms-transform:rotate(90deg);
      transform:rotate(90deg);
    }
    

    Fiddle example

    Note the negative margin-left on the container, which adjusts the position after rotation - that needs to match the container "height" (i.e. the max-width property). The max-height property represents the maximum "width" that the container will reach before being clipped. The overflow:hidden is needed to force the container to grow to contain its floating child elements.

    Also, note that because the area divs are now floated, the margins between them won't collapse. One way of solving that is to restrict the margins to only two sides (I've used right and bottom) and then emulate the margins for the other sides via padding on the container with box-sizing:border-box.

    Finally, in this particular example the area divs have a 1:1 aspect ratio, which means we don't have to worry about repositioning them after the rotation. Things become slightly more complicated if their width and height are different.

    This solution won't work on older versions of IE, but it at least supports IE9.

提交回复
热议问题