flex 常用布局

发布时间 2023-10-25 14:03:37作者: 林财钦

一、背景

由于本人对样式很是头疼,一些常用的样式用就百度,所以整理下常用的样式.

二、实现

flex 一个靠左一个靠右

image

一个靠左一个靠右
<body>
  <div>
    <!-- 父盒子 -->
    <div class="father_box">
      <!-- 第一个盒子 -->
      <div>我是最左边的内容</div>
      <!-- 第二个盒子 -->
      <div class="right_box">我是最右边的盒子</div>
    </div>
  </div>
</body>
<style scoped>
.father_box {
  background: cornflowerblue;
  color: #fff;
  display: flex;
}
.right_box {
  margin-left: auto;
}
</style>

flex 一个居中一个靠左

image

方式一

一个居中一个靠左
<body>
  <div>
    <div class="maxBox">
      <div class="leftBox">左边</div>
      <div class="centerBox">中间</div>
      <!-- 重点在第三个是一个空盒子且名字要跟第一个盒子的名字一致 -->
      <div class="leftBox"></div>
    </div>
  </div>
</body>
<style scoped>
/* 最大的盒子 */
.maxBox {
  display: flex;
  background-color: cornflowerblue;
  color: white;
}
/* 第一个盒子 */
.leftBox {
  flex: 1;
}
/* 第二个盒子 */
.centerBox {
  text-align: center;
}
</style>

一个居中一个靠右

image

一个居中一个靠右
<body>
  <div>
    <div class="maxBox">
      <div class="leftBox"></div>
      <div class="centerBox">中间</div>
      <!-- 重点在第三个是一个空盒子且名字要跟第一个盒子的名字一致 -->
      <div class="leftBox">11</div>
    </div>
  </div>
</body>
<style scoped>
/* 最大的盒子 */
.maxBox {
  display: flex;
  background-color: cornflowerblue;
  color: white;
}
/* 第一个盒子 */
.leftBox {
  flex: 1;
  text-align:right

}
/* 第二个盒子 */
.centerBox {
  text-align: center;
}
</style>

方式二

点击查看代码
<body>
  <div>
    <div class="maxBox">
      <div class="leftBox"></div>
      <div class="centerBox">中间</div>
      <!-- 重点在第三个是一个空盒子且名字要跟第一个盒子的名字一致 -->
      <div class="leftBox">最右</div>
    </div>
  </div>
</body>
<style scoped>
/* 最大的盒子 */
.maxBox {
  display: flex;
  background-color: cornflowerblue;
  color: white;
}
/* 第一个盒子 */
.leftBox {
margin-left: auto;


}
/* 第二个盒子 */
.centerBox {
  text-align: center;
}
</style>

比如有三个元素:

<div>
  <div></div>
  <div></div>
  <div></div>
</div>

最外层的设置display:flex,水平排列,子元素前两个靠左,第三个靠右

有两种方式实现,第三个元素设置(上面两种方式总结)

// 方法一
		margin-left: auto;
// 方法二
		flex: 1;
		text-align:right

三、遇到的报错

四、参考博客

https://blog.51cto.com/u_15274085/5820635