2014-08-29 110 views
0

让我们得到开门见山,我创造了这个例子跨越,以更好地让我的观点:影响父只

Demo Here

HTML: 表1

<table class="testClass"> 
    <tr> 
     <td>Inner table 
      <table> 
       <tr> 
        <td>Hello</td> 
        <td>Testing testing</td> 
        <td>Bye</td> 
       </tr> 
      </table> 
     </td> 
    </tr> 
</table> 
<br /> 
<br /> 
<br />Table 2 
<table class="testClass"> 
    <tr> 
     <td colspan="3">stuff</td> 
    </tr> 
    <tr> 
     <td>Left</td> 
     <td>Middle</td> 
     <td>Right</td> 
    </tr> 
</table> 

CSS:

table { 
    border: 2px solid red; 
    width: 100%; 
} 
td { 
    border: 2px solid blue; 
} 
/* Relative CSS */ 
.testClass tr:last-child td:nth-child(1) { 
    width: 15px; 
} 
.testClass tr:last-child td:nth-child(2) { 
    width: auto; 
} 
.testClass tr:last-child td:nth-child(3) { 
    width: 15px; 
} 

所以我们有2个表,两个表都是相同的类。 Table 1有一个表格,其中Table 2没有。

我发现这个问题是使用我创建的CSS,我无法停止受影响的子表(内表).testClass的样式。我认为:not()可以使用,但我无法找到解决方案,我觉得这应该不是那么难。

是否有可能只影响从父进入子表的样式中的父亲?

注意:只能更改CSS而不是HTML。 CSS3可以使用!

我希望这是有道理的,如果我需要使它更清晰,请发表评论。

+0

为什么不使用类似'.testClass> tr ...'的东西来设计只有可怕ct孩子?像[this](http://jsfiddle.net/urryfof5/2/)。 – Harry 2014-08-29 09:51:00

+2

@Harry这应该是'.testClass> tr,。testClass> tbody> tr',因为大多数现代浏览器都会自动插入表格主体。 – feeela 2014-08-29 09:53:17

+0

@feeela:是的,好点。 – Harry 2014-08-29 09:55:50

回答

2

选择第一级孩子并应用它。

.testClass > tbody > tr:last-child > td:nth-child(1) { 
     width: 15px; 
    } 
    .testClass > tbody > tr:last-child > td:nth-child(2) { 
    width: auto; 
    } 
    .testClass > tbody > tr:last-child > td:nth-child(3) { 
     width: 15px; 
    } 

DEMO

+0

这阻止了表2获取样式[Demo](http://jsfiddle.net/urryfof5/5/) – Ruddy 2014-08-29 09:55:36

+1

Mate,请参考feeela在问题中的评论,'tbody'也是必需的,因为大多数浏览器都会添加它默认。 – Harry 2014-08-29 10:18:45

+1

我已经更新了我的答案。谢谢Harry。 – 2014-08-29 10:21:15

0

您可以添加样式声明样

table table { border: none; } 

从父table -declaration覆盖样式。这样,没有嵌套的表格会有边框。 td同样适用。

另一个解决方案是:

table:not(.testClass) { 
    border: 0px none; 
} 

这消除边界为做应用了testClass所有表。我测试并看到了这项工作(在下面的小提琴的另一个版本中)。

这里有一个拨弄你的代码有两个附加声明,消除边界内部表: http://jsfiddle.net/erlingormar/bk6m4w5d/#base

0

也许是这样的:http://jsfiddle.net/urryfof5/7/

基本上你调用从最后一个子表body和add>,所以它不会影响里面的嵌套表格:

body > table:last-child (and follow it with your css) 
+0

请在您的答案中包含代码并解释您所做的事情。哦,知道,这是用身体,对不起,我没有看。页面上有大量表格,这是行不通的。 – Ruddy 2014-08-29 10:00:19