CSS实现文本居中和块级元素居中

一、单行文本水平垂直居中

1.文本水平居中:给文本的父盒子设置text-align: center;即可
2.文本垂直居中: 给文本设置line-height的值与父盒子height的值相等

<style>
  .box {
    width: 200px;
    height: 200px;
    background-color: palegreen;
    text-align: center;
    line-height: 200px;
  }
</style>
<div class="box">
  box
</div>

3.利用弹性盒模型,设置align-item:center;justify-content:center;实现文本水平垂直居中

<style>
  .box {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 200px;
    height: 200px;
    background-color: palegreen;
  }
</style>
<div class="box">
  box
</div>

二、块级元素水平垂直居中

方法一:
父元素相对定位+子元素绝对定位+手动计算margin

<style>
  .box {
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -100px;
    margin-left: -100px;
    width: 200px;
    height: 200px;
    background-color: palegreen;
  }
</style>
<div class="box"></div>

方法二:
父元素相对定位+子元素绝对定位+transform

<style>
  .box {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 200px;
    height: 200px;
    background-color: palegreen;
  }
</style>
<div class="box"></div>

方法三:
父元素相对定位+子元素绝对定位+ top:0;right:0;bottom:0;left:0; +margin:auto

<style>
  .box {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    width: 200px;
    height: 200px;
    background-color: palegreen;
  }
</style>
<div class="box"></div>

方法四:
给父盒子设置display:flex;开启弹性布局,然后设置align-item:center;justify-content:center;

<style>
  body {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .box {
    width: 200px;
    height: 200px;
    background-color: palegreen;
  }
</style>
<div class="box"></div>
  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值