使用display : inline-block+vertical-align 进行布局为何不能实现多行文本垂直水平居中?

ba64bff3d221ff2a7e6befbf6f8c5e55_auto-orient,1.png

 
<div class="parent">
    <span class="child">测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例</span>
  </div>
  <style>
    .parent {
      height: 100px;
      background-color: aqua;
      text-align: center; /*水平居中*/
      line-height: 100px; /* 通过 line-height 设置幽灵节点的基线 */
    }
    .child {
      color: #fff;
      background-color: blueviolet;
      vertical-align: middle;
      line-height: normal; /* 块级元素时需要加 */
      display: inline-block; /* 重点,要把 line-height 设置成 normal, 要不然会继承100 */
    }
  </style>

设置幽灵节点的高度以及幽灵节点的基线(通过line-height),来设置幽灵节点的x-height,是span的中线与幽灵节点的中线对齐,同样也可以使vertical-align:middle;居中

请问是哪里出错了呢?请赐教,不胜感激。

阅读 3.1k
4 个回答

我觉得是可以的,然后我复制到codepen看了下,真的是可以的

又新建了html文件,然后挂了。。一想,肯定有古怪,把文档结构补全,然后就又行了。

<!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>Document</title>
</head>
<body>
   
<div class="parent">
  <span class="child">测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例测试示例</span>
</div>
<style>
  .parent {
    height: 100px;
    background-color: aqua;
    text-align: center; /*水平居中*/
    line-height: 100px; /* 通过 line-height 设置幽灵节点的基线 */
  }
  .child {
    color: #fff;
    background-color: blueviolet;
    vertical-align: middle;
    line-height: normal; /* 块级元素时需要加 */
    display: inline-block; /* 重点,要把 line-height 设置成 normal, 要不然会继承100 */
  }
</style>
</body>
</html>

CSS 的属性 vertical-align 用来指定行内元素(inline)或表格单元格(table-cell)元素的垂直对齐方式。详情请查看:
https://developer.mozilla.org...

只不是没有指定doctype
<!DOCTYPE html>

你这个例子中,真正使它居中的是line-height

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题