【CSS 布局】水平垂直方向居中

【CSS 布局】水平垂直方向居中

单行元素

html 复制代码
<div class="container">
    <div class="item"></div>
</div>
  • 方式一:relativeabsolute
css 复制代码
.container {
  position: relative;
  height: 400px;
  border: 1px solid #ccc;
  .item {
    position: absolute;
    width: 200px;
    height: 200px;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: auto;
    border: 1px solid #ccc;
  }
}
  • 方式二:relativeabsolute(变种,适合于宽高固定)
css 复制代码
.container {
  position: relative;
  height: 400px;
  border: 1px solid #ccc;
  .item {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-bottom: -100px;
    width: 200px;
    height: 200px;
    border: 1px solid #ccc;
  }
}
  • 方式三:flexmargin
css 复制代码
.container {
  display: flex;
  height: 400px;
  border: 1px solid #ccc;
  .item {
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
    margin: auto; /* 关键点 */ 
  }
}
  • 方式四:flex
css 复制代码
.container {
  display: flex;
  height: 400px;
  border: 1px solid #ccc;
  justify-content: center;
  align-items: center;
  .item {
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
  }
}
  • 方式五:flex
css 复制代码
.container {
  display: flex;
  height: 400px;
  border: 1px solid #ccc;
  justify-content: center;
  .item {
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
    align-self: center;
  }
}

多行元素

html 复制代码
<div class="container">
    <img src="./login.png" alt="" />
    <p>欢迎访问我的个人博客 hhmax.xyz</p>
    <button>按钮</button>
</div>
css 复制代码
.container {
  height: 400px;
  border: 1px solid #ccc;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}
相关推荐
竹林8188 分钟前
从 RPC 超时到批量签名:我用 @solana/web3.js 重构了一个 NFT 铸造页面,踩了这些坑
前端·javascript
工业HMI实战笔记19 分钟前
工业HMI界面布局“1核2辅”黄金结构,适配90%场景
前端·ui·性能优化·自动化·交互
林希_Rachel_傻希希1 小时前
web性能优化之————图片效果
前端·javascript·面试
Darling噜啦啦1 小时前
前端存储与 this 指向完全指南:从 LocalStorage 实战到 call/apply/bind 深度解析
前端·javascript
wei1986211 小时前
.net添加web引用和添加服务引用有什么区别?
java·前端·.net
格子软件2 小时前
2026年GEO优化系统源码级状态机与多模型调度拆解
java·前端·vue.js·人工智能·vue·geo
HUMHSX3 小时前
Vue 项目启动全流程解析:从入口文件到全局指令注册与页面渲染
前端·javascript·vue.js
有颜有货3 小时前
PMC生产排产的4种算法,一次讲清
java·服务器·前端
小虎牙0073 小时前
Android kotlin图片库Coil源码详解
android·前端
随风一样自由3 小时前
【前端领域】前端开发核心应用场景与落地实践
前端·前端框架