CSS——垂直水平居中


一、垂直居中

transform方法,calc方法

元素高度已知的情况下,可以使用calc函数动态计算达到垂直居中所需高度
calc(50%-?px),?为自身高度一半
calc为css3新增,可以使用top: 50%; margin-top: -?px; 代替

.center {
  height: 300px;
  background: #f00;
}
.center div {
  position: relative;
  width: 100px;
  height: 100px;
  background: #0ff;
  top: calc(50% - 150px);
}

元素高度未知的情况,可以使用 transform中的translate参数对元素自身进行平移
translate参数是以元素本身的宽高为基准,所以向上平移自身高度50%的距离即可实现垂直居中
子元素必须要加上position:relative,否则无效

.center {
  height: 1000px;
  background: #f00;
}
.center div {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

flex方法

使用flex布局,将align-items参数设定为居中即可

.center {
  display: flex;
  align-items: center;
  height: 300px;
  background: #f00;
}
.center div {
  width: 100px;
  height: 100px;
  background: #0ff;
}

line-height方法

该方法仅适用于“单行”的“行内元素”

.center {
  height: 100px;
  background: #f00;
  line-height: 100px;
  text-align: center;
}
.center div {
  display: inline-block;
  background: #0ff;
}

伪元素(::after,::before)方法

面对多行的元素时可以使用此方法解决垂直居中问题

.center {
  height: 300px;
  background: #f00;
  text-align: center;
}
.center::after {
  content: "";
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}
.center div {
  height: 100px;
  width: 100px;
  display: inline-block;
  vertical-align: middle;
  background: #0ff;
}

绝对定位(margin:auto)方法

使用绝对定位方法,将元素的position指定为absolute,父元素的position必须要指定为relative
将top,left,right,bottom都设置为0,让子盒子与父容器的间距为0
top,left,right,bottom属性只在position存在且不为"static"时生效

.center {
  position: relative;
  height: 300px;
  background: #f00;
}
.center div {
  height: 100px;
  width: 100px;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  background: #0ff;
}

二、水平居中

行内元素

.center{
  text-align:center;
}

块级元素

元素宽度已知,直接使用margin

.center {
  width: 100px;
  margin: 0 auto;
  background-color: #f00;
}

元素宽度未知,将元素设为display:table

.center {
  display: table;
  margin: 0 auto;
  background-color: #f00;
}

其他方法

水平居中与垂直居中多数方法的使用是类似的,在flex布局中使用justify-content:center;即可实现水平居中
使用position + calc,position +transform,以及绝对定位设四方间距为0,margin:auto的方法均可实现


总结

在平常学习中对于垂直居中问题,使用flex和transform的次数较多,今天总结了更多解决方法,在不同环境下使用对应的方法以便更妥善的解决问题,对于各类方法的基础使用有所掌握,对于部分方法的实现原理和弊端还不太了解,等工作之后深入学习再加以扩展。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值