9.1

238 阅读1分钟

今天页面出现了应该样式被覆盖的问题。查了下是因为子元素的 line-height 被设置为 1,本来是继承父元素的 line-height 的。 导致了文字没有垂直居中,出现了样式错乱的情况。

跟下面代码很类似的场景,文字本来是居中显示的,然后触发了别的组件懒加载,该组件的部分样式又是全局的,没有加 scope 从而导致给 span 添加了 line-height: 1; 的样式

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .content {
      height: 500px;
      background-color: #eee;
      color: #fff;
    }
    .line {
      display: flex;
      height: 100px;
      line-height: 100px;
      margin: 0 auto;
      font-size: 36px;
    }
    .name, .value{
      text-align: center;
      flex: 1;
    }

  </style>
  <title>Document</title>
</head>
<body>
  <div class="content">
    <div class="line">
      <span class="name">
        name
      </span>
      <span class="value">
        value
      </span>
    </div>
    <button onclick="addStyle()">添加样式</button>
  </div>
</body>
<script>
  function addStyle(params) {
    console.log('addStyle');
    var link = document.createElement('link');
    link.rel = "stylesheet";
    link.href = "index.css";
    document.getElementsByTagName('head')[0].appendChild(link);
  }
</script>
</html>
/* 同一目录下的 index.css 文件 */
span {
  line-height: 1;
}

上面的代码触发 addStyle 函数时样式则出现覆盖。

解决方式

/* 添加样式的权值 */
.content .line span {
  line-height: 100px;
}
span {
  line-height: 100px !important;
}

/* 不使用 line-height 去垂直居中 */
.line {
  align-items: center;
}

还有就是 vue 打包方式的区别,使用 mode 为 prod 的正式包才会出现这个问题,这个等明天有空再搞。

出现的几个问题:

  • 不了解样式继承的机制,习惯性以为把 line-height 权值提高就行,而忽略了在控制台看到的样式,明明只是个标签样式怎么会影响到你类名下的样式嘛,还傻傻的只知道加权值
  • 不了解 flex 布局的 align-items 的使用