How to float 3 divs side by side using CSS?

2019-01-01 16:44发布

I know how to make 2 divs float side by side, simply float one to the left and the other to the right.

But how to do this with 3 divs or should I just use tables for this purpose?

标签: css css-float
15条回答
余欢
2楼-- · 2019-01-01 17:22

@Leniel this method is good but you need to add width to all the floating div's. I would say make them equal width or assign fixed width. Something like

.content-wrapper > div { width:33.3%; }

you may assign class names to each div rather than adding inline style, which is not a good practice.

Be sure to use a clearfix div or clear div to avoid following content remains below these div's.

You can find details of how to use clearfix div here

查看更多
浅入江南
3楼-- · 2019-01-01 17:25

It is same way as you do for the two divs, just float the third one to left or right too.

<style>
  .left{float:left; width:33%;}
</style>

<div class="left">...</div>
<div class="left">...</div>
<div class="left">...</div>
查看更多
步步皆殇っ
4楼-- · 2019-01-01 17:27
<br style="clear: left;" />

that code that someone posted up there, it did the trick!!! when i paste it just before closing the Container DIV, it helps clear all subsequent DIVs from overlapping with the DIVs i've created side-by-side at the top!

<div>
<div class="left"></div>
<div class="left"></div>
...
...
<div class="left"></div>
<!--  then magic trick comes here  -->
<br style="clear: left;" />
</div>

tadaa!! :)

查看更多
永恒的永恒
5楼-- · 2019-01-01 17:29

The modern way is to use the CSS flexbox, see support tables.

.container {
  display: flex;
}
.container > div {
  flex: 1; /*grow*/
}
<div class="container">
  <div>Left div</div>
  <div>Middle div</div>  
  <div>Right div</div>
</div>

You can also use CSS grid, see support tables.

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr; /* fraction*/
}
<div class="container">
  <div>Left div</div>
  <div>Middle div</div>  
  <div>Right div</div>
</div>

查看更多
高级女魔头
6楼-- · 2019-01-01 17:29

you can float: left for all of them and set the width to 33.333%

查看更多
回忆,回不去的记忆
7楼-- · 2019-01-01 17:34

But does it work in Chrome?

Float each div and set clear;both for the row. No need to set widths if you dont want to. Works in Chrome 41,Firefox 37, IE 11

Click for JS Fiddle

HTML

<div class="stack">
    <div class="row">
        <div class="col">
            One
        </div>
        <div class="col">
            Two
        </div>
    </div>
        <div class="row">
        <div class="col">
            One
        </div>
        <div class="col">
            Two
        </div>
                    <div class="col">
            Three
        </div>
    </div>
</div>

CSS

.stack .row { 
clear:both;

}
.stack .row  .col    {
    float:left;
      border:1px solid;

}
查看更多
登录 后发表回答