前端面试之水平居中、垂直居中、水平垂直居中总结

首先定义两个盒子,并添加基础样式

<div class="father">
      <div class="son"></div>
</div>
<style>
 1. {
  padding: 0;
  margin: 0;
}
.father {
  height: 200px;
  width: 800px;
  background-color: skyblue;
}
.son {
  height: 100px;
  width: 200px;
  background-color: orange;
}
</style>

水平居中

  1. flex布局
.father {
  display: flex;
  justify-content: center;
}
  1. 子绝父相 + transform
.father {
  position: relative;
}
.son {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}
  1. inline-block + text-align:center
.father {
  text-align: center;
}
.son {
  display: inline-block;
}
  1. flex + margin: 0 auto
.father {
  display: flex;
}
.son {
  margin: 0 auto;
}
  1. table + margin: 0 auto
.son {
  display: table;
  margin: 0 auto;
}

样式:
在这里插入图片描述

垂直居中

  1. flex布局
.father {
  display: flex;
  align-items: center;
}
  1. 子绝父相 + transform
.father {
  position: relative;
}
.son {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
  1. flex + margin: auto 0
.father {
  display: flex;
}
.son {
  margin: auto 0;
}
  1. table-cell + vertical-align: middle
.father {
  display: table-cell;
  vertical-align: middle;
}

样式:
在这里插入图片描述

水平垂直居中

  1. flex布局
.father {
  display: flex;
  align-items: center;
  justify-content: center;
}
  1. 子绝父相 + transform
.father {
  position: relative;
}
.son {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
  1. flex + margin: auto
.father {
  display: flex;
}
.son {
  margin: auto;
}
  1. inline-block + text-align: center + table-cell + vertical-align: middle
.father {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.son {
  display: inline-block;
}

样式:
在这里插入图片描述

最后解释一下margin:auto

块级元素设置居中的前提是设置了width,若在css中没写width则会默认占据100%的宽度。auto是指平分剩余空间。
如果单单使用margin:auto是不能实现垂直方向上的居中的,因为默认垂直方向上是没有剩余空间的,这里有两种方法使margin:auto在垂直方向上平分剩余空间

  1. 子绝父相后 + margin:auto,子元素四边都设为0,子元素会填充真个父元素的所有剩余空间
.father {
  position: relative;
}
.son {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}
  1. flex + margin:auto,可以快速实现水平垂直居中(推荐flex布局,很方便)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩浩不睡觉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值