CSS: Set divs horizontally in 2 rows

折月煮酒 提交于 2019-12-01 09:23:55

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

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>

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).

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!