行高等于高只能让单行文本垂直居中,及让多行垂直居中的方法

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>行高等于高只能让单行文本垂直居中</title></title>
  <style>
    /* 优化前 */
    .box {
      width: 150px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      margin-bottom: 100px;
      border: 1px solid red;

    }
    /* 优化后 */
    /* 多行文本垂直对齐的几种方法 */
    /* 方法1.父元素设置display: table; 子元素设置display: table-cell; vertical-align: middle; */
    /* .box {
      display: table;
      width: 150px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      margin-bottom: 100px;
      border: 1px solid red;

    }
    .box span {
      display: table-cell;
      vertical-align: middle;
    } */
     /* 方法2.父元素设置line-height: 50px; 子元素设置display: inline-block;
      vertical-align: middle;
      line-height: 18px; */
     /* .box {
      width: 150px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      margin-bottom: 100px;
      border: 1px solid red;

    }
    .box span {
      display: inline-block;
      vertical-align: middle;
      line-height: 18px;
    } */
    /* 方法3.父元素设置高度line-height: 150px; 子元素设置display: inline-block;
      position: relative;
      top:50%;
      transform: translateY(-50%)*/
    .box {
      width: 150px;
      height: 150px; 
      text-align: center;
      margin-bottom: 100px;
      border: 1px solid red;

    }
    .box span {
      display: inline-block;
      position: relative;
      top:50%;
      transform: translateY(-50%);
    }
    /* 方法4.父元素弹性布局 定义flex 子项的对齐方式align-items: center*/
    /* .box {
      display: flex;
      width: 150px;
      height: 150px; 
      text-align: center;
      margin-bottom: 100px;
      border: 1px solid red;

    } */
    


    .imgbox {
      width: 300px;
      height: 200px;
      line-height: 200px;
    }
    .imgbox img {
      /* 设置元素与文本 垂直对齐 */
      vertical-align: middle; 
    }
  </style>
</head>
<body>
  <div class='box'>
    <span>猥琐发育,别浪<br>
    稳住我们能赢</span>
    
  </div>
  <div class="imgbox">
    <img src="./1.png" alt="">
    用户名
  </div>
</body>
</html>

效果图:

优化前

优化后:

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值