前端 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>
相关推荐
倾颜18 小时前
从 textarea 到 AI 输入框:用 Tiptap 实现 / 命令、@ 引用和结构化请求
前端·langchain·next.js
kyriewen19 小时前
程序员连夜带团队跑路,省了23万:这AI太贵,真的用不起了
前端·javascript·openai
kyriewen20 小时前
你写的代码没有测试,就像出门不锁门——Jest + Testing Library 从入门到不慌
前端·单元测试·jest
yuzhiboyouye21 小时前
web前端英语面试
前端·面试·状态模式
canonical_entropy1 天前
下一代低代码渲染框架 nop-chaos-flux 的设计原则
前端·低代码·前端框架
东方小月1 天前
5分钟搞懂Harness Engineering(驾驭工程):从提示词到AI Agent的进化之路
前端·后端·架构
我叫黑大帅1 天前
为什么需要 @types/react?解决“无法找到模块 react 的声明文件”报错
前端·javascript·面试
之歆1 天前
DAY_21JavaScript 深度解析:数组(Array)与函数(Function)(一)
前端·javascript
XinZong1 天前
【AI社交】基于OpenClaw自研轻量化AI社交平台实战
前端
Le_ee1 天前
ctfweb:php/php短标签/.haccess+图片马/XXE
开发语言·前端·php