多行文字垂直居中实现--四种方法

1. 将父元素设置为块级表格来显示display:table;子元素设置为表格单元格 来显示,设置vertical-align: middle。

<div style="margin: 20px auto;width: 400px;height: 400px;background-color: aqua;overflow: hidden;">
    <div style="display: table;margin: 100px auto;width: 200px;height: 200px;text-align: center;background-color: antiquewhite;">
      <span style="display: table-cell;vertical-align: middle;">你好你好你好你好你好你好你好你好你好你好你好</span>
    </div>
  </div>

2. 先对父元素设置高度和行高(相等)height=line-height,子元素设置 为行内块元素display:inline-block,设置vertical-align: middle,自定义line-height 属性的值18px;

<div style="margin: 20px auto;width: 400px;height: 400px;background-color: aqua;overflow: hidden;">
    <div style="display: table;margin: 100px auto;width: 200px;height: 200px;text-align: center;background-color: antiquewhite;">
      <span style="display: table-cell;vertical-align: middle;">你好你好你好你好你好你好你好你好你好你好你好</span>
    </div>
  </div>

3. 先将子元素设置为行内块元素display:inline-block,再对子元素设置相对 定位position:relative,之后利用top:50%transform:translateY(-50%)设置 平移

<div style="margin: 20px auto;width: 400px;height: 400px;background-color: rgb(254, 164, 181);overflow: hidden;">
    <div style="margin: 100px auto;width: 200px;height: 200px;text-align: center;background-color: antiquewhite;">
      <span style="display: inline-block;position: relative;top: 50%;transform: translateY(-50%);">你好你好你好你好你好你好你好你好你好你好你好</span>
    </div>
  </div>

4. 利用flex弹性布局,将父元素设置为弹性盒子,并设置父元素align-items: center,即定义flex子项在flex容器侧轴方向上的对齐方式为center。

  <div style="margin: 20px auto;width: 400px;height: 400px;background-color: rgb(254, 229, 164);overflow: hidden;">
    <div style="display: flex;align-items: center;margin: 100px auto;width: 200px;height: 200px;text-align: center;background-color: antiquewhite;">
      <span>你好你好你好你好你好你好你好你好你好你好你好</span>
    </div>
  </div>

效果:

 

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值