【问题标题】:Font color in a table doesn't inherit from parent div表格中的字体颜色不会从父 div 继承
【发布时间】:2014-06-17 07:46:28
【问题描述】:

例如,我有一个字体颜色设置为紫色的 div,div 中的一些文本继承了颜色,但有些不是,例如在一张桌子上。 (以下代码另存为test.html并在浏览器中打开进行测试)

<div style="color: purple;">
  <p>Some text</p> <!-- text here is purple -->
  <table>
    <tr>
      <td>Table cell 1</td> <!-- text here is NOT purple -->
      <td>Table cell 2</td> <!-- text here is NOT purple -->
    </tr>
  </table>
  Another text <!-- text here is purple -->
</div>

如果我将 div 替换为 body,它们会继承。

<body style="color: purple;">
  <p>Some text</p> <!-- text here is purple -->
  <table>
    <tr>
      <td>Table cell 1</td> <!-- text here is purple -->
      <td>Table cell 2</td> <!-- text here is purple -->
    </tr>
  </table>
  Another text <!-- text here is purple -->
</body>

我想知道:

  1. 他们为什么以及如何不从父容器继承样式?
  2. 是否有其他解决方法可以使内容元素继承字体颜色,就好像它们继承自正文一样?

【问题讨论】:

标签: html css inheritance


【解决方案1】:

这个“问题”是由于您没有声明文档类型,导致浏览器以 Quirks 模式运行。

其中一个结果就是您在此处看到的情况:表格元素获得了color: -webkit-text; 样式,该样式覆盖了从父 div 继承的内容。

添加:

<!DOCTYPE html>

在您的文档顶部将导致浏览器呈现您想要的页面。

【讨论】:

  • 这正是我想要的。非常感谢!
  • 在我的例子中,这是一个 PHP 警告,插入到 DOCTYPE 之前...
  • 不敢相信 Hacker News 没有这个声明
  • 直到 2018 年我才知道这一点。谢谢。
【解决方案2】:
  1. 他们为什么以及如何不从父容器继承样式?

    似乎浏览器特定的样式正在应用于&lt;table&gt; 元素。

  2. 是否有其他解决方法可以使内容元素继承字体颜色,就好像它们继承自正文一样?

    要覆盖它,只需将以下内容添加到您的 css 中

    table{
     color:inherit;
    }
    

【讨论】:

    【解决方案3】:

    您的 css 样式被您拥有的另一个样式表中的表格 css 覆盖。

    将此添加到您的 css 文件中

    #purple, table{
        color: purple;
    } 
    

    或者让表格继承你的div的css

    table {
       color: inherit; 
    }
    

    这个到你的html

    <div style="color: purple;">
      <p>Some text</p> <!-- text here is purple -->
      <table>
        <tr>
          <td>Table cell 1</td> <!-- text here is NOT purple -->
          <td>Table cell 2</td> <!-- text here is NOT purple -->
        </tr>
      </table>
      Another text <!-- text here is purple -->
    </div>
    

    这是一个工作示例:http://jsfiddle.net/36aZ8/

    【讨论】:

      【解决方案4】:

      试试这个

      将 css 也添加到表中

           <style> 
               #divc,table{
              color: purple;
              } 
      
              </style>
      
          <div id="divc">
            <p>Some text</p> <!-- text here is purple -->
            <table>
              <tr>
                <td>Table cell 1</td> <!-- text here is NOT purple -->
                <td>Table cell 2</td> <!-- text here is NOT purple -->
              </tr>
            </table>
      
        Another text <!-- text here is purple -->
      </div>
      

      http://jsfiddle.net/T7JBB/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多