【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;
}
相关推荐
一位搞嵌入式的 genius21 分钟前
从 ES6 到 ESNext:JavaScript 现代语法全解析(含编译工具与实战)
前端·javascript·ecmascript·es6
linweidong2 小时前
C++ 模块化编程(Modules)在大规模系统中的实践难点?
linux·前端·c++
leobertlan6 小时前
2025年终总结
前端·后端·程序员
子兮曰6 小时前
OpenClaw架构揭秘:178k stars的个人AI助手如何用Gateway模式统一控制12+通讯频道
前端·javascript·github
百锦再7 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
莲华君7 小时前
React快速上手:从零到项目实战
前端·reactjs教程
百锦再7 小时前
React编程高级主题:测试代码
android·前端·javascript·react.js·前端框架·reactjs
易安说AI7 小时前
Ralph Loop 让Claude无止尽干活的牛马...
前端·后端
失忆爆表症9 小时前
05_UI 组件库集成指南:Shadcn/ui + Tailwind CSS v4
前端·css·ui
小迷糊的学习记录9 小时前
Vuex 与 pinia
前端·javascript·vue.js