CSS: Set divs horizontally in 2 rows

前端 未结 4 703
一向
一向 2021-01-14 09:40

Lets say I have

1
2
相关标签:
4条回答
  • 2021-01-14 10:06

    I don't think you can do that with css with structure as you have.

    This structure should help you to get your required layout:

    <div class="a">
       <div class="b">
           <div class="c">1</div>
           <div class="c">2</div>
       </div>
       <div class="b">
           <div class="c">3</div>
           <div class="c">4</div>
       </div>
    </div>
    
    
    <style>
    div.a div.b {float: left; width: 100px;}
    </style>
    
    0 讨论(0)
  • 2021-01-14 10:17

    There is a CSS property that does exactly that

    http://tinker.io/8ff59

    .cont {
        -webkit-columns: 5em;
        -moz-columns: 5em;
        columns: 5em; /* desired width of column */
    }
    

    http://caniuse.com/#feat=multicolumn

    0 讨论(0)
  • 2021-01-14 10:18

    I accomplished this with CSS here using this code: It's kind of hackish though.

    I set three of the divs (the last three) to the class 'double'

    .cont .single {
        background: blue;
        color: white;
        width: 100px;
        height: 100px;
        margin: 10px;
        float:left;
        display: inline-block;
    }
    .cont .double {
        background: blue;
        color: white;
        width: 100px;
        height: 100px;
        margin: 10px;
        display:inline-block;
        float:left;
    }
    
    div:nth-child(5) {
        clear:left;
    }
    
    .cont {
        height: 220px;
        background: red;
    }
    
    0 讨论(0)
  • 2021-01-14 10:25

    For the sake of argument, let's say you can't change your document structure - you need to do this through layout definitions alone.

    If you know how many items you will have, the easiest way to manage this would be CSS3 columns with inline-block elements. Your .singles are the inline-blocks, and .cont uses the 'columns' property to set 5 columns each wide enough to hold your singlets, whilst using max-height to force the inline-blocks onto new columns every two items. The singlets have a min-size large enough to stop multiple inline-blocks displaying on the same line.

    You can see this effect as a jsfiddle here: http://jsfiddle.net/mwjJG/25/ :

    .container {
        height: 240px;
    
        columns: 100px 5;
        -webkit-columns: 100px 5;
        -moz-columns: 100px 5;
        }
    
    .single {
        display: inline-block;
        height: 100px;
        width: 100px;
        }
    

    Do be aware this won't work on IE<10 unless you can use some kind of JS-based shiv to add support for the columns property (CSS Pie may be able to do this).

    0 讨论(0)
提交回复
热议问题