【问题标题】:How to spread out elements with float:left property evenly如何使用 float:left 属性均匀分布元素
【发布时间】:2020-12-18 05:28:04
【问题描述】:

我有一个容器 div。 在它里面我有所有的子 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;
}

【问题讨论】:

  • 使用弹性盒子,更简单
  • 如果你想均匀分布它,为什么要float: left?使用flexboxjustify-content: space-evenly
  • 这个问题是在一次采访中被问到的。我找不到任何关于此的文章。
  • flexbox 是你的朋友!

标签: css dom sass css-selectors less


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 2011-05-05
    • 2017-04-14
    • 1970-01-01
    • 2016-03-20
    • 2013-06-02
    相关资源
    最近更新 更多