css居中的几种方法_CSS几种常用的水平垂直居中对齐方法

文字的水平垂直居中

class="content"> <p>文字水平垂直居中p> </div>
.content{  width: 400px;  height: 100px;  border: #000000 solid 1px;}

当前效果:

d9e53be94e698bb64d1b3702fcd5b5c3.png

.content{  width: 400px;  height: 100px;  border: #000000 solid 1px;  text-align: center;  line-height: 100px;}

文字水平垂直居中效果:

1e6bafefff67388d4b5333ddc500ef4b.png

元素的水平垂直居中

class="content"> <div class="box">盒子居中div></div>
.content{    margin: 20px auto;    width: 300px;    height: 300px;    border: #000000 solid 1px;  }  .box{    width: 120px;    height: 120px;    line-height: 120px;    text-align: center;    background: red;  }

当前效果:

4d0ce84a8c8416d7fe30575ce0f9b28f.png

01使用绝对定位
.content{  position: relative;  margin: 20px auto;  width: 300px;  height: 300px;  border: #000000 solid 1px;}.box{  position: absolute;  top:0;  left: 0;  bottom: 0;  right: 0;  width: 120px;  height: 120px;  line-height: 120px;  margin: auto;  text-align: center;  background: red;}

居中效果:

af2d93f15680f96084eeb2724d013a5c.png

02使用绝对定位+calc()
.box{  position: absolute;  top:calc(50% - 120px / 2);  left: calc(50% - 120px / 2);  width: 120px;  height: 120px;  line-height: 120px;  text-align: center;  background: red;}

居中效果:

af2d93f15680f96084eeb2724d013a5c.png

03使用绝对定位+transform()
.box{  position: absolute;  top: 50%;  left: 50%;  transform: translate(-50%, -50%);  width: 120px;  height: 120px;  line-height: 120px;  text-align: center;  background: red;}

居中效果:

af2d93f15680f96084eeb2724d013a5c.png

04使用CSS3弹性盒模型
/*作用于父元素*/.content{  display: flex;/*弹性布局*/  justify-content: center;/*水平居中*/  align-items: center;/*垂直居中*/  position: relative;  margin: 20px auto;  width: 300px;  height: 300px;  border: #000000 solid 1px;}.box{  width: 120px;  height: 120px;  line-height: 120px;  text-align: center;  background: red;}

居中效果:

af2d93f15680f96084eeb2724d013a5c.png

扫码关注 青春正当时

66f11b79af6d29eb94e4a77d38270f1c.png

4e9d97725084d89314816ef1e47f7e55.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值