优化实战 第 58 期 - CSS 的继承性及其应用

2,197 阅读1分钟

继承性CSS 非常重要的一个特性,如果一个属性具备继承性,那么在该元素上设置后,它的后代元素都可以继承这个属性

如果后代元素自己有设置该属性,那么优先使用后代元素自己的属性,不管继承过来的属性权重有多高

表单元素样式重置

  • 重置作用

    表单元素默认不会继承字体和颜色的样式,需要使用 inherit 关键字手动对其进行初始化重置

    提升开发效率,减少冗余代码

  • 重置代码

    html {
      font-size: 14px;
      color: #666;
    }
    input, select, textarea, button {
      font: inherit;
      color: inherit;
    }
    

创建提示框,让小箭头自动继承背景和边框的样式

  • 参照效果

    bubble.jpg

  • 示例代码

    <div class="callout">提示框内容</div>
    
    .callout {
      position: relative;
      padding: .6rem;
      background-color: #fff;
      border: 1px solid #e5e5e5;
      border-radius: 4px;
    }
    .callout::before {
      content: '';
      position: absolute;
      top: -.4rem; left: 1rem;
      padding: .35rem;
      border: inherit;
      background: inherit;
      border-right: 0;
      border-bottom: 0;
      transform: rotate(45deg);
    }
    

    一起学习,加群交流看 沸点