【问题标题】:How can I override inline styles on contained elements with CSS?如何使用 CSS 覆盖包含元素的内联样式?
【发布时间】:2021-01-31 01:28:03
【问题描述】:

在下面的 sn-p 中,我想覆盖内联样式,所以 h1,h2,h3,h4 标签具有写在 CSS 文件中的样式。

  • 我不能/不允许删除内联样式(它由名为 Froala 的 HTML 编辑器生成)
  • 我们不知道应用于哪个元素的内联样式,它可能是 h 标记本身或 span 或任何其他子/嵌套元素。
  • 我们不知道存在多少嵌套元素。
  • 为方便起见,我们可以假设内联样式始终应用于span,但span 可以是第n 个孩子

.wrapper{}
h1,h2,h3,h4 {line-height:1.5 !important;} 
h1,h2 > span {color:rgb(41,105,176) !important;}
h3,h4 > span {color:rgb(184, 49, 47) !important;}
<div class="wrapper">
  <h1>Dyspepsi</h1>
  <h2><span style="color: rgb(0,0,0);">Dyspepsi</span></h2>
  <h1><strong><em><span style="color: rgb(0,0,0); line-height:2.5">Dyspepsi</span></em></strong></h1>
  <h2><strong><em><span style="color: rgb(0,0,0);">Dyspepsi</span></em></strong></h2>
  <h3><strong><span style="color: rgb(0,0,0); border-bottom: 1px solid;">Dyspepsi</span></strong></h3>
  <h4><strong><em><span style="color: rgb(0,0,0);">Dyspepsi</span></em></strong></h4>
</div>
  
  

【问题讨论】:

    标签: html css css-selectors inline-styles


    【解决方案1】:

    除了常规的 h1 到 h4 选择器之外,您还可以将“全部”选择​​器 * 与标题选择器组合使用(作为子项),并在所有这些选择器上加上 !important

    h1, h1 *,
    h2, h2 *,
    h3, h3 *,
    h4, h4 * {
      line-height: 1.5 !important;
    }
    
    h1, h1 *,
    h2, h2 * {
      color: rgb(41, 105, 176) !important;
    }
    
    h3, h3 *,
    h4, h4 * {
      color: rgb(184, 49, 47) !important;
    }
    <div class="wrapper">
      <h1>Dyspepsi</h1>
      <h2><span style="color: rgb(0,0,0);">Dyspepsi</span></h2>
      <h1><strong><em><span style="color: rgb(0,0,0); line-height:2.5">Dyspepsi</span></em></strong></h1>
      <h2><strong><em><span style="color: rgb(0,0,0);">Dyspepsi</span></em></strong></h2>
      <h3><strong><span style="color: rgb(0,0,0); border-bottom: 1px solid;">Dyspepsi</span></strong></h3>
      <h4><strong><em><span style="color: rgb(0,0,0);">Dyspepsi</span></em></strong></h4>
    </div>

    【讨论】:

    • 感谢您的回答,为什么在这种情况下第一个h1 标签没有上色?
    • 啊,我监督了这一点 - 只是相应地编辑了我的答案:这个例子中的 h1 不是子元素,所以我现在将所有标题标签作为选择器添加到这些 CSS 规则中。
    • line-height:2.5 也保留在第三行
    • 非常感谢,你救了我:)
    猜你喜欢
    • 1970-01-01
    • 2016-12-17
    • 2013-05-24
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多