前端 CSS 经典:flex + margin 布局

前言:如今我们布局大多时候都是用的 flex 布局,但是有时我们也可以使用 margin 小技巧去完成布局。在弹性盒中当我们把 margin 某一个方向上设置为 auto,他的含义是用 margin 吃掉这个方向的剩余空间。

1. 元素垂直和水平居中

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="initial-scale=1.0, user-scalable=no, width=device-width"
    />
    <title>document</title>
    <style>
      .box {
        width: 500px;
        height: 500px;
        border: 1px solid;
        display: flex;
      }
      .item {
        width: 100px;
        height: 100px;
        background: blue;
        margin: auto;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <div class="item"></div>
    </div>
    <script></script>
  </body>
</html>

2. 三个子元素,两个居左一个居右

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="initial-scale=1.0, user-scalable=no, width=device-width"
    />
    <title>document</title>
    <style>
      .box {
        width: 500px;
        height: 500px;
        border: 1px solid;
        display: flex;
      }
      .item {
        width: 100px;
        height: 100px;
        background: blue;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <div class="item"></div>
      <div class="item"></div>
      <div class="item" style="margin-left: auto"></div>
    </div>
    <script></script>
  </body>
</html>
相关推荐
apcipot_rain5 小时前
【应用密码学】实验五 公钥密码2——ECC
前端·数据库·python
ShallowLin5 小时前
vue3学习——组合式 API:生命周期钩子
前端·javascript·vue.js
Nejosi_念旧5 小时前
Vue API 、element-plus自动导入插件
前端·javascript·vue.js
互联网搬砖老肖5 小时前
Web 架构之攻击应急方案
前端·架构
pixle06 小时前
Vue3 Echarts 3D饼图(3D环形图)实现讲解附带源码
前端·3d·echarts
麻芝汤圆6 小时前
MapReduce 入门实战:WordCount 程序
大数据·前端·javascript·ajax·spark·mapreduce
juruiyuan1118 小时前
FFmpeg3.4 libavcodec协议框架增加新的decode协议
前端
读心悦8 小时前
CSS结构性伪类、UI伪类与动态伪类全解析:从文档结构到交互状态的精准选择
css·ui·交互
Peter 谭8 小时前
React Hooks 实现原理深度解析:从基础到源码级理解
前端·javascript·react.js·前端框架·ecmascript
LuckyLay10 小时前
React百日学习计划——Deepseek版
前端·学习·react.js