【问题标题】:CSS Specificity issue in HTML tableHTML表格中的CSS特异性问题
【发布时间】:2013-09-01 11:03:10
【问题描述】:

我有一个 base.css,它具有以下 CSS:

.table thead tr th, table th { 
    text-align:left; 
    font-size: 11px;
    font-weight: bold; 
    color: #333; 
    padding: 4px; 
    background-color: #EEE; 
    border: #FFF solid; 
    border-width: 1px 1px 0 0;  
    border-left: #e7e7e7; 
    white-space:nowrap;  }

我已经在我的 JSP 中包含了这个 CSS。但我需要与base.css 中的颜色不同的颜色,所以我声明如下:

#demo table.header tr {
    background:#FDBB30
}

在我的 JSP 中。我之前遇到过这个问题,并发现了 CSS Specificity。第一个的特异性是0,0,1,5,第二个的特异性是0,1,1,2。根据它,表格应该呈现第二个 CSS。但事实并非如此。有什么建议.. ?我无法删除 base.css 我需要它用于其他元素。

我的桌子是这样的:

<table cellpadding="0" cellspacing="0" border="0" align="left" width="100%">
   <thead>
      <!-- Column Naming for the table -->
      <tr>
         <th class="header">SName</th>
         <th class="header">Report</th>
         <th class="header">Owner</th>
         <th class="header">STime</th>
         <th class="header">SFreq</th>
         <th class="header">SDate</th>
         <th class="header">EDate</th>
         <!-- <th>Action</th> -->
      </tr>
   </thead>
</table>

【问题讨论】:

    标签: html css html-table css-selectors


    【解决方案1】:

    这个选择器是错误的

    #demo table.header tr
    

    首先我没有看到任何demo id 声明在那里,table.header 也不正确,这意味着选择tableheader 类,但因为你正在将该类应用于th选择器将失败。

    table 元素上调用class

    <table class="header" cellpadding="0" cellspacing="0" border="0" align="left" width="100%" >
    

    还要确保你有一个包装器元素,例如一个div,id 为demo


    还是不习惯上面的东西,只需在你的table 上使用id 就可以了

    <table id="change_color" ...>
    

    然后使用下面的选择器

    #change_color thead tr {
       background: #f00;
    }
    

    Demo

    【讨论】:

      【解决方案2】:

      不要在 tr 上应用自定义 CSS,而是在 th 上应用它。像这样:

      #demo th.header {
         background:#FDBB30
      }
      

      同样在您的 HTML 中,确保您已将 id="demo" 用于您的 table 或包含 tablediv

      这个demo on JSFiddle 可能会有所帮助。

      【讨论】:

        【解决方案3】:

        除了 CSS 选择器中的错误(请参阅其他答案)之外,还有一个简单的事实,即表格单元格中的背景是在表格行的背景“顶部”绘制的,因此无论是否tr上的特异性要高得多!

        如果 HTML 是

        <table id="table">
            <tr id="tr"><th>hello</th></tr>
        </table>
        

        CSS 是

        th {background:cyan}
        body table#table tr#tr {background:yellow !important}
        

        背景仍然是青色的!见fiddle

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-02-02
          • 1970-01-01
          • 1970-01-01
          • 2019-07-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-11
          相关资源
          最近更新 更多