【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;
}
相关推荐
o***Z44820 小时前
前端性能优化案例
前端
张拭心20 小时前
前端没有实际的必要了?结合今年工作内容,谈谈我的看法
前端·ai编程
姜太小白20 小时前
【前端】CSS媒体查询响应式设计详解:@media (max-width: 600px) {……}
前端·css·媒体
HIT_Weston20 小时前
39、【Ubuntu】【远程开发】拉出内网 Web 服务:构建静态网页(二)
linux·前端·ubuntu
百***060120 小时前
SpringMVC 请求参数接收
前端·javascript·算法
天外天-亮20 小时前
Vue + excel下载 + 水印
前端·vue.js·excel
起个名字逛街玩20 小时前
前端正在走向“工程系统化”:从页面开发到复杂产品架构的深度进化
前端·架构
用户479492835691521 小时前
React 渲染两次:是 Bug 还是 Feature?聊聊严格模式的“良苦用心”
前端·react.js·前端框架
b***748821 小时前
前端GraphQL案例
前端·后端·graphql
云飞云共享云桌面21 小时前
无需配置传统电脑——智能装备工厂10个SolidWorks共享一台工作站
运维·服务器·前端·网络·算法·电脑