清淨
  • Java

    • Java 基础
  • 框架

    • Flyway
    • MapStruct
    • Spring Cloud
  • 中间件

    • Elasticsearch
    • Redis
    • RabbitMQ
    • Kafka
  • 三剑客

    • HTML
    • CSS
    • JavaScript
  • 进阶

    • jQuery
    • ECMAScript6
    • TypeScript
  • Vue

    • Vue2
    • Vue3
    • VuePress
  • Linux
  • Jenkins
  • Maven
  • MySQL
  • 插件工具
  • 代码集成
  • 其它

    • 数据结构与算法
    • 计算机网络
    • 操作系统
    • 设计模式
迁移日志
订阅号
微信订阅号
微信订阅号
GitHub
  • Java

    • Java 基础
  • 框架

    • Flyway
    • MapStruct
    • Spring Cloud
  • 中间件

    • Elasticsearch
    • Redis
    • RabbitMQ
    • Kafka
  • 三剑客

    • HTML
    • CSS
    • JavaScript
  • 进阶

    • jQuery
    • ECMAScript6
    • TypeScript
  • Vue

    • Vue2
    • Vue3
    • VuePress
  • Linux
  • Jenkins
  • Maven
  • MySQL
  • 插件工具
  • 代码集成
  • 其它

    • 数据结构与算法
    • 计算机网络
    • 操作系统
    • 设计模式
迁移日志
订阅号
微信订阅号
微信订阅号
GitHub
  • CSS

    • 常用
    • 选择器
    • 字体
    • 浮动
    • 定位
    • 背景
    • 渐变
    • 表格
    • Hack
    • 居中
    • 过渡(transition)
    • 动画(animation)
    • 变形(transform)
    • 弹性布局(flex)
    • Less
    • 媒体查询

居中

  • 水平居中

    方式一就是直接使用 margin: 0 auto;, 方式二是使用绝对定位:

    <div class="d1">
      <div class="d2"></div>
    </div>
    
    .d1 {
      width: 200px;
      height: 200px;
      background: #ff6600;
      /* position: sticky;
      top: 10px; */
      position: relative;
      margin: 200px auto 0;
    }
    
    /* 此方式仅使用于设置了元素的宽高 ,另一种居中方式请见 笔记的 translate  */
    .d2 {
      width: 100px;
      height: 100px;
      background: #e3f98d;
      position: absolute;
      /* 必须要设置 left 和 right 为0*/
      left: 0;
      right: 0;
      margin: 0 auto;
    }
    
  • 垂直居中

    方式一也是使用绝对定位:

    <div class="d1">
      <div class="d2"></div>
    </div>
    
    .d1 {
      width: 200px;
      height: 200px;
      background: #ff6600;
      /* position: sticky;
      top: 10px; */
      position: relative;
      margin: 200px auto 0;
    }
    
    .d2 {
      /* 此方式仅使用于设置了元素的宽高 ,另一种居中方式请见 笔记的 translate  */
      width: 100px;
      height: 100px;
      background: #e3f98d;
      position: absolute;
      /* 必须要设置 top 和 bottom 为0*/
      top: 0;
      bottom: 0;
      margin: auto 0;
    }
    
  • 垂直水平都居中

    综合了以上两种方式:

    <div class="d1">
      <div class="d2"></div>
    </div>
    
    .d1 {
      width: 200px;
      height: 200px;
      background: #ff6600;
      /* position: sticky;
      top: 10px; */
      position: relative;
      margin: 200px auto 0;
    }
    
    /* 此方式仅使用于设置了元素的宽高 ,另一种居中方式请见 笔记的 translate  */
    .d2 {
      width: 100px;
      height: 100px;
      background: #e3f98d;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
    }
    

使用 margin: 0 auto; 时,该元素必须设置 width 属性。

想要编辑此页?
上次更新: 2025/6/3 23:09
贡献者: Junfeng Dai
←Hack过渡(transition)→
[ 纸上得来终觉浅绝知此事要躬行 ]
Copyright © 2021-present Junfeng Dai
蜀ICP备2021009537号