【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;
}
相关推荐
明天好,会的4 小时前
分形生成实验(五):人机协同破局--30万token揭示Actix-web状态管理的微妙边界
运维·服务器·前端
C_心欲无痕4 小时前
nginx - alias 和 root 的区别详解
运维·前端·nginx
我是苏苏6 小时前
Web开发:C#通过ProcessStartInfo动态调用执行Python脚本
java·服务器·前端
无羡仙7 小时前
Vue插槽
前端·vue.js
用户6387994773058 小时前
每组件(Per-Component)与集中式(Centralized)i18n
前端·javascript
SsunmdayKT8 小时前
React + Ts eslint配置
前端
开始学java8 小时前
useEffect 空依赖 + 定时器 = 闭包陷阱?count 永远停在 1 的坑我踩透了
前端
zerosrat8 小时前
从零实现 React Native(2): 跨平台支持
前端·react native
狗哥哥8 小时前
🔥 Vue 3 项目深度优化之旅:从 787KB 到极致性能
前端·vue.js