div button垂直居中_前端布局之——水平垂直居中

本文详细介绍了前端布局中div button的垂直居中方法,包括行内元素居中、margin、flex布局等多种策略,并展示了不同方法的示意图。内容覆盖了水平居中、垂直居中及水平垂直居中的多种实现方式,如绝对定位、flex和grid等,为开发者提供了丰富的布局解决方案。
摘要由CSDN通过智能技术生成

其他平台文章地址

  • github:
前端布局之——水平垂直居中 · Issue #3 · yaodebian/blog​github.com
714b80866bb4a90d48fff24d70a7be7f.png
  • csdn:
https://blog.csdn.net/YaoDeBiAn/article/details/100907015​blog.csdn.net

前端页面的居中是平常开发中比较常见的布局,以下将从水平居中垂直居中水平垂直居中三个角度分析不同的布局方法。

水平居中

法一:行内元素水平居中

html:
<div class="container">
  <div class="box"></div>
</div>

css:
.container {
  text-align: center;
  width: 100%;
  height: 400px;
  background: #ccc;
}

.container .box {
  width: 100px;
  height: 100px;
  background: yellow;
  display: inline-block;
}

示意图:

e8547036a61c81db00cc3d536330f380.png

法二:margin实现水平居中

html:
<div class="container">
  <div class="box"></div>
</div>

css:
.container {
  width: 100%;
  height: 400px;
  background: #ccc;
}

.container .box {
  width: 100px;
  height: 100px;
  background: yellow;
  margin: 0 auto;
}

示意图:

e8547036a61c81db00cc3d536330f380.png

法三:flex弹性布局(可实现多个块级元素水平居中)

html:
<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

css:
.container {
  width: 100%;
  height: 400px;
  background: #ccc;
  display: flex;
  justify-content: center;
}

.container .box {
  width: 100px;
  height: 100px;
  background: yellow;
  margin-left: 10px;
}

.container .box:first-child {
  margin-left: 0;
}

示意图:

7d62da37d12917d846e2701f4b0beccd.png

注意:flex布局会将margin包含在内,并且上面的场景通过text-align: center;同样可以做到,也就是方法一。

垂直居中

法一:行内元素垂直居中

html:
<div class="container">
  <div class="box"></div>
</div>

css:
.container {
  width: 100%;
  height: 400px;
  line-height: 400px;
  background: #ccc;
}

.container .box {
  width: 100px;
  height: 100px;
  background: yellow;
  display: inline-block;
  vertical-align: middle;
}

演示图:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值