CSS选择器仅选择外部元素

时间:2016-02-24 08:34:51

标签: html css css-selectors

我的html以下:

table.classA, table.classA th, table.classA td {
    //beautiful css here
}

我想做的是仅格式化外部表格,并排除内部表格。

我使用的当前CSS选择器是:

super

但是上面的选择器会选择classA表中的所有元素。 那我怎么能这样做呢?

5 个答案:

答案 0 :(得分:3)

试试这个

table.classA, table.classA > thead > tr > th, table.classA > tbody > tr > td {
    //beautiful css here
}

答案 1 :(得分:3)

您可以使用直接子选择器>。并将您的选择器转换为:

table.classA, table.classA > tr > th, table.classA > tr > td {
    //beautiful css here
}

这将仅定位<tr>内的直接父级为tableclassA的元素。

现在,可悲的是,这种&#34;有这个父母&#34;选择器的类型通常不利于CSS性能(因为它必须上升整个DOM树并检查元素的父级)。我建议大量使用课程。

答案 2 :(得分:2)

  

据我所知,最多应该有2个级别

table.classA > *, table.classA > * > th, table.classA > * > td {
    //Css
}

选择table.classA和第二个孩子thtd

中的所有第一个孩子

答案 3 :(得分:0)

更简单的方法是使用类

调用所需的元素

你像这样转换你的HTML

<table class="tableclassA">
   <tbody>
      <tr class="trclassA">
         <td class="tdclassA">
         </td>
      </tr>
      <tr class="trclassA">
         <td class="tdclassA">
            <table>
               <tbody>
                  <tr>
                     <td>
                     </td>
                  </tr>
               </tbody>
            </table>
         </td>
      </tr>
   </tbody>
</table>

然后在你的CSS中

tableclassA, trclassA, tdclassA {
    //beautiful css here
}

答案 4 :(得分:0)

您可以将表格包装在div标签内,然后按照下面的说明进行操作。 HTML现在将成为

<div id="container">
<table class="classA">
   <tbody>
      <tr>
         <td>
         </td>
      </tr>
      <tr>
         <td>
            <table>
               <tbody>
                  <tr>
                     <td>
                     </td>
                  </tr>
               </tbody>
            </table>
         </td>
      </tr>
   </tbody>
</table>
</div>

Ans然后,只能使用以下css选择器

将样式应用于外部表
#container > table.classA, #container > table.classA th, #container > table.classA td {
//beautiful css here
}

注1:'&gt;'用于仅选择CSS层次结构中最顶层的子项。 注意2:你也可以在容器div上使用class而不是ID,但主要思想是在父元素中包含。

相关问题