如何使用float:left属性均匀分布元素

问题描述

我有一个容器div。 在它里面,我所有的子div都具有float left属性。 如何将孩子div均匀地排在整个行上?

代码笔如下: https://codepen.io/pranavbhagwat81/pen/NWNgaVW

<div class='Box'>
    <div class='Box1'></div>
    <div class='Box2'></div>
    <div class='Box3'></div>
 </div>

  CSS
.Box{

}
.Box1{
  height:50px;
  width:50px;
  background-color:violet;
  float:left;
}
.Box2{
  height:50px;
  width:50px;
  background-color:indigo;
  float:left;
}
.Box3{
  height:50px;
  width:50px;
  background-color:green;float:left;
}

解决方法

使用space-between(或space-evenly)代替flex:

.box {
  display: flex;
  justify-content: space-between;
}
.box > * {
  height: 50px;
  width: 50px;
}

.box1 {
  background-color: violet;
}

.box2 {
  background-color: indigo;
}

.box3 {
  background-color: green;
}

.box4 {
  background-color: orange;
}

.box5 {
  background-color: yellow;
}

.box6 {
  background-color: red;
}

.box7 {
  background-color: black;
}

.box8 {
  background-color: pink;
}
<div class='box'>
  <div class='box1'></div>
  <div class='box2'></div>
  <div class='box3'></div>
  <div class='box4'></div>
  <div class='box5'></div>
  <div class='box6'></div>
  <div class='box7'></div>
  <div class='box8'></div>
</div>

如果您不能使用flex,则可以calc来确定应留出的边距:

.box > * {
  height: 50px;
  width: 50px;
  float: left;
}
.box > *:not(:first-child) {
  margin-left: calc((100vw - 50px * 8) / 8)
}

.box1 {
  background-color: violet;
}

.box2 {
  background-color: indigo;
}

.box3 {
  background-color: green;
}

.box4 {
  background-color: orange;
}

.box5 {
  background-color: yellow;
}

.box6 {
  background-color: red;
}

.box7 {
  background-color: black;
}

.box8 {
  background-color: pink;
}
<div class='box'>
  <div class='box1'></div>
  <div class='box2'></div>
  <div class='box3'></div>
  <div class='box4'></div>
  <div class='box5'></div>
  <div class='box6'></div>
  <div class='box7'></div>
  <div class='box8'></div>
</div>