【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;
}
相关推荐
x***r1513 分钟前
Notepad++ 8.6 安装教程:详细步骤+自定义安装路径(附注意事项)
linux·前端·javascript
Hilaku6 分钟前
为什么很多工作 5 年的前端,身价反而卡住了?🤷‍♂️
前端·javascript·面试
ai超级个体6 分钟前
前端下午茶:这 3 个网页特效建议收藏(送源码)
前端·three.js·threejs·网页设计·vibe coding·网页灵感·网页分享
维斯186 分钟前
VueFlow 图自适应容器尺寸教程
前端
helloweilei7 分钟前
next/dynamic和React.lazy的区别
前端·next.js
Aaron_Feng10 分钟前
一个小工具解决Swift Actor重入问题
前端
笨笨狗吞噬者11 分钟前
维护 uniapp 小程序端近一年,我想拉一个开发者交流群
前端·程序员·uni-app
前端炒粉17 分钟前
React 面试高频题
前端·react.js·面试
程序员陆业聪18 分钟前
让 Android 里的 AI 真正「干活」:Function Calling 工程实现全解
前端
mumuWorld20 分钟前
解决openclaw以及插件安装的报错
前端·ai编程