居中个人总结

垂直居中

对于单行文本
height和line-height设置相同高度

.p {
  height: 20px;
  line-height: 20px
}

不定高

.father {
  positon: relative;
}
.son {
  position: absolute;
  top: 50%;
  transform: transiate(0, -50%);
}
.father {
  positon: relative;
}
.son {
  position: absolute;
  top: 0;
  bottom: 0;
  marigin: auto;
}

flex布局 + align-items: center;

水平居中

对于给定宽度,可以简单使用margin: 0 auto;

.center {
  width: 960px;
  margin: 0 auto;
}

或者在父元素中添加text-align:center;子元素添加display: inline-block;

.father {
  width: 300ox;
  text-align: center;
}
.son{
  display: inline-block;
}

更多方法浏览https://www.w3cplus.com/css/elements-horizontally-center-with-css.html

垂直水平居中

HTML:

<div class="set">
   <div class="con"></div>
<div>

需要知道元素的宽高

.con{
  width: 100px;  
  height: 100px;
  position: absolute; 
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
.con{
  width: 100px; 
  height: 150px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -75px;
  margin-left: -50px;
}

或者把父元素改为display: table-cell

.set{
  width: 300px;
   height: 300px;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

或者使用flex布局

.set{
  width: 300px;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

or

#box {
  position: absolute;
  width: 100px;
  height: 100px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值