前端 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>
相关推荐
FL162386312938 分钟前
室内易燃物识别易燃评估室内易燃程度识别分割数据集labelme格式1015张85类别
java·服务器·前端
用户0595401744638 分钟前
把 AI 长期记忆去重测试从 20 分钟压到 40 秒,重复率从 18% 干到 1.5%
前端·css
kyriewen1 小时前
我把 AI 写的并发请求控制器手写了一遍——3 个语义我当时根本讲不清
前端·javascript·面试
_codemonster2 小时前
Vue中的ref和reactive到底在干嘛
前端·javascript·vue.js
IT_陈寒2 小时前
为什么我的JavaScript闭包总是漏掉那个变量?
前端·人工智能·后端
两只羊ovo2 小时前
前端八股之 storage & this:两个最容易卡住的点,一次讲透
前端
用户921080262862 小时前
Bubble 打字机效果实践:从项目配置到源码实现
前端
weixin_461408583 小时前
npm npx yarn
开发语言·前端·javascript
四千岁3 小时前
RAG系统中的分块
前端·javascript·后端